aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/tests/common/config_stub.rs
blob: 7566b897a923548d6d7765490b3be1b223c1800b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//! Configurable Config stub, equivalent to PHPUnit's
//! `getMockBuilder(Config::class)` where `get('x')` is stubbed via
//! `->method('get')->willReturn(y)`.
//!
//! `Config` is a concrete (non-trait) struct, so rather than mocking it we build a
//! real `Config` and seed the requested keys through `Config::merge`, which is how
//! `get('key')` actually resolves its value. This keeps the stub faithful to the
//! real resolution logic instead of intercepting `get`.
#![allow(dead_code)]

use std::cell::RefCell;
use std::rc::Rc;

use indexmap::IndexMap;
use shirabe::config::Config;
use shirabe_php_shim::PhpMixed;

pub struct ConfigStubBuilder {
    use_environment: bool,
    base_dir: Option<String>,
    // Config values to seed, applied via Config::merge under the `config` section.
    values: IndexMap<String, PhpMixed>,
    source: String,
}

impl Default for ConfigStubBuilder {
    fn default() -> Self {
        Self {
            use_environment: false,
            base_dir: None,
            values: IndexMap::new(),
            source: Config::SOURCE_UNKNOWN.to_string(),
        }
    }
}

impl ConfigStubBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn use_environment(mut self, value: bool) -> Self {
        self.use_environment = value;
        self
    }

    pub fn base_dir(mut self, base_dir: impl Into<String>) -> Self {
        self.base_dir = Some(base_dir.into());
        self
    }

    /// Sets the value `Config::get(key)` will return. Equivalent to PHPUnit's
    /// `->method('get')->with(key)->willReturn(value)`.
    pub fn with(mut self, key: impl Into<String>, value: PhpMixed) -> Self {
        self.values.insert(key.into(), value);
        self
    }

    pub fn build(self) -> Config {
        let mut config = Config::new(self.use_environment, self.base_dir);
        if !self.values.is_empty() {
            let mut merge: IndexMap<String, PhpMixed> = IndexMap::new();
            merge.insert("config".to_string(), PhpMixed::Array(self.values));
            config.merge(&merge, &self.source);
        }
        config
    }

    pub fn build_shared(self) -> Rc<RefCell<Config>> {
        Rc::new(RefCell::new(self.build()))
    }
}

// For testing only. Convenience for the common case of a default `Config(false)`.
pub fn get_config_stub() -> Config {
    ConfigStubBuilder::new().build()
}