1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.intentresolver.validation.types
17 
18 import com.android.intentresolver.validation.Importance
19 import com.android.intentresolver.validation.Invalid
20 import com.android.intentresolver.validation.NoValue
21 import com.android.intentresolver.validation.Valid
22 import com.android.intentresolver.validation.ValidationResult
23 import com.android.intentresolver.validation.Validator
24 import com.android.intentresolver.validation.ValueIsWrongType
25 import kotlin.reflect.KClass
26 import kotlin.reflect.cast
27 
28 class SimpleValue<T : Any>(
29     override val key: String,
30     private val expected: KClass<T>,
31 ) : Validator<T> {
32 
validatenull33     override fun validate(source: (String) -> Any?, importance: Importance): ValidationResult<T> {
34         val value: Any? = source(key)
35         return when {
36             // The value is present and of the expected type.
37             expected.isInstance(value) -> return Valid(expected.cast(value))
38 
39             // No value is present.
40             value == null ->
41                 when (importance) {
42                     Importance.WARNING -> Invalid() // No warnings if optional, but missing
43                     Importance.CRITICAL -> Invalid(NoValue(key, importance, expected))
44                 }
45 
46             // The value is some other type.
47             else ->
48                 Invalid(
49                     listOf(
50                         ValueIsWrongType(
51                             key,
52                             importance,
53                             actualType = value::class,
54                             allowedTypes = listOf(expected)
55                         )
56                     )
57                 )
58         }
59     }
60 }
61