aboutsummaryrefslogtreecommitdiff
path: root/lib/Config.pm6
blob: 729ccba60f355fd266a352c47fbd4a7ea060197a (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#! /usr/bin/env false

use v6.c;

use Config::Exception::UnsupportedTypeException;
use Config::Exception::UnknownTypeException;
use Config::Exception::FileNotFoundException;
use Config::Type;
use Config::Parser;

class Config is export
{
    has $!content = {};
    has $!path;
    has $!parser;

    multi method read()
    {
        return self.load($!path);
    }

    multi method read(Str $path, Str $parser? = "")
    {
        Config::Exception::FileNotFoundException.new.throw() unless $path.IO.f;

        $!parser = self.get-parser($path, $parser);

        require ::($!parser);
        $!content = ::($!parser).read($path);

        return True;
    }

    multi method read(Hash $hash)
    {
        $!content = $hash;
    }

    method write(Str $path, Str $parser? = "")
    {
        $parser = self.get-parser($path, $parser);

        require ::($parser);
        return ::($parser).write($path, $!content);
    }

    method get(Str $key, Any :$default = Nil)
    {
        my $index = $!content;

        for $key.split(".") -> $part {
            return $default unless defined($index{$part});

            $index = $index{$part};
        }

        $index;
    }

    method has(Str $key) {
        my $index = $!content;

        for $key.split(".") -> $part {
            return False unless defined($index{$part});

            $index = $index{$part};
        }

        True;
    }

    method set(Str $key, Any $value)
    {
        my $index := $!content;

        for $key.split(".") -> $part {
            $index{$part} = {} unless defined($index{$part});

            $index := $index{$part};
        }

        $index = $value;

        self;
    }

    method get-parser(Str $path, Str $parser? = "")
    {
        if ($parser ne "") {
            return $parser;
        }

        my $type = self.get-parser-type($path);

        Config::Exception::UnknownTypeException.new.throw() if $type eq Config::Type::unknown;

        "Config::Parser::" ~ $type;
    }

    method get-parser-type(Str $path)
    {
        given ($path) {
            when .ends-with(".yml") { return Config::Type::yaml; };
        }

        my $file = $path;

        if (defined($path.index("/"))) {
            $file = $path.split("/")[*-1];
        }

        if (defined($file.index("."))) {
            return $file.split(".")[*-1];
        }

        return Config::Type::unknown;
    }
}