Certainly! Below is a Kotlin Spring Boot equivalent of your PHP Symfony enrichConfig function. This translation assumes you have a service class that interacts with an AftershipClient to retrieve courier data.
PHP Symfony Code Recap
public function enrichConfig(array $config): array
{
$slug = trim($config['slug'] ?? '');
Assert::notWhitespaceOnly($slug, 'A slug should be provided in the config for Aftership');
$carrierList = $this->client->getCouriers();
/** @var array{slug?: string|null, required_fields?: array<string>} $carrierData */
foreach ($carrierList as $carrierData) {
if (($carrierData['slug'] ?? null) === $slug) {
/** @var array{slug: string, required_fields?: array<string> } $enrichedConfig */
$enrichedConfig = array_merge(
$config,
array_fill_keys($carrierData['required_fields'] ?? [], null)
);
return $enrichedConfig;
}
}
throw new InvalidArgumentException(sprintf('Slug "%s" does not exist in Aftership API', $slug));
}
Kotlin Spring Boot Translation
First, ensure you have the necessary dependencies in your build.gradle.kts or pom.xml, such as Spring Boot Starter and any assertion libraries you prefer.
1. Define the Data Classes
Assuming the structure of the carrier data returned by the AftershipClient:
data class CarrierData(
val slug: String?,
val requiredFields: List<String>? = emptyList()
)
2. Define the AftershipClient Interface
This client is responsible for interacting with the Aftership API to fetch couriers.
interface AftershipClient {
fun getCouriers(): List<CarrierData>
}
3. Implement the Service
Create a service that contains the enrichConfig function.
import org.springframework.stereotype.Service
import org.springframework.util.Assert
@Service
class AftershipService(private val client: AftershipClient) {
/**
* Enriches the provided config map by adding required fields based on the carrier's slug.
*
* @param config A map containing configuration details, including a "slug" key.
* @return A new map with the original config merged with the required fields set to null.
* @throws IllegalArgumentException if the slug is missing or does not exist in the Aftership API.
*/
fun enrichConfig(config: Map<String, Any?>): Map<String, Any?> {
// Extract and trim the slug from the config
val slug = (config["slug"] as? String)?.trim().orEmpty()
// Assert that slug is not blank
Assert.hasText(slug, "A slug should be provided in the config for Aftership")
// Retrieve the list of carriers from the client
val carrierList = client.getCouriers()
// Find the carrier matching the slug
val carrierData = carrierList.find { it.slug == slug }
?: throw IllegalArgumentException("Slug \"$slug\" does not exist in Aftership API")
// Extract required fields or use an empty list if none are specified
val requiredFields = carrierData.requiredFields ?: emptyList()
// Create a map with required fields set to null
val filledFields = requiredFields.associateWith { null }
// Merge the original config with the filled fields
return config + filledFields
}
}
4. Usage Example
Here's how you might use the AftershipService in a controller or another service:
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/config")
class ConfigController(private val aftershipService: AftershipService) {
@PostMapping("/enrich")
fun enrichConfig(@RequestBody config: Map<String, Any?>): ResponseEntity<Map<String, Any?>> {
return try {
val enrichedConfig = aftershipService.enrichConfig(config)
ResponseEntity.ok(enrichedConfig)
} catch (e: IllegalArgumentException) {
ResponseEntity.badRequest().body(mapOf("error" to e.message))
}
}
}
5. Explanation of the Kotlin Code
-
Extracting the Slug:
val slug = (config["slug"] as? String)?.trim().orEmpty()
- Safely casts the
slug value to a String, trims it, and defaults to an empty string if null.
-
Assertion:
Assert.hasText(slug, "A slug should be provided in the config for Aftership")
- Ensures that the
slug is not empty or blank. Throws an IllegalArgumentException if the assertion fails.
-
Fetching and Finding the Carrier:
val carrierData = carrierList.find { it.slug == slug }
?: throw IllegalArgumentException("Slug \"$slug\" does not exist in Aftership API")
- Searches for the carrier with the matching
slug. Throws an exception if not found.
-
Merging Configurations:
val filledFields = requiredFields.associateWith { null }
return config + filledFields
- Creates a new map where each required field key is mapped to
null and merges it with the original config map.
6. Handling Configuration Maps in Kotlin
In Kotlin, Map<String, Any?> is immutable by default. If you need a mutable map, you can use MutableMap<String, Any?> and apply changes accordingly. However, in this example, we're returning a new immutable map by merging existing entries with the required fields.
7. Exception Handling
The Kotlin version throws an IllegalArgumentException similar to the PHP version's InvalidArgumentException. Ensure that your application has appropriate global exception handlers if you want to manage these exceptions uniformly.
Complete Example in Context
Putting it all together, here's a complete Kotlin Spring Boot service with the necessary components:
// CarrierData.kt
data class CarrierData(
val slug: String?,
val requiredFields: List<String>? = emptyList()
)
// AftershipClient.kt
interface AftershipClient {
fun getCouriers(): List<CarrierData>
}
// AftershipService.kt
import org.springframework.stereotype.Service
import org.springframework.util.Assert
@Service
class AftershipService(private val client: AftershipClient) {
fun enrichConfig(config: Map<String, Any?>): Map<String, Any?> {
val slug = (config["slug"] as? String)?.trim().orEmpty()
Assert.hasText(slug, "A slug should be provided in the config for Aftership")
val carrierList = client.getCouriers()
val carrierData = carrierList.find { it.slug == slug }
?: throw IllegalArgumentException("Slug \"$slug\" does not exist in Aftership API")
val requiredFields = carrierData.requiredFields ?: emptyList()
val filledFields = requiredFields.associateWith { null }
return config + filledFields
}
}
// ConfigController.kt
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/config")
class ConfigController(private val aftershipService: AftershipService) {
@PostMapping("/enrich")
fun enrichConfig(@RequestBody config: Map<String, Any?>): ResponseEntity<Map<String, Any?>> {
return try {
val enrichedConfig = aftershipService.enrichConfig(config)
ResponseEntity.ok(enrichedConfig)
} catch (e: IllegalArgumentException) {
ResponseEntity.badRequest().body(mapOf("error" to e.message))
}
}
}
Notes
-
Null Safety: Kotlin's type system helps prevent NullPointerExceptions by enforcing null safety. Ensure that your data classes and method signatures accurately reflect which fields can be nullable.
-
Immutability: The use of immutable maps promotes safer code by avoiding unintended side effects.
-
Error Messages: Customize error messages as needed to provide clearer feedback to API consumers.
-
Unit Testing: Consider writing unit tests for the enrichConfig function to ensure it behaves as expected under various scenarios.
Feel free to adjust the code based on the specific details and requirements of your application!