diff options
author | Patrick Spek <p.spek@tyil.nl> | 2017-04-23 21:24:26 +0200 |
---|---|---|
committer | Patrick Spek <p.spek@tyil.nl> | 2017-04-23 21:24:26 +0200 |
commit | 9687382b803ec0dc5a7dd55be88b53a4264215f9 (patch) | |
tree | e522d65c4555acabcc282e87e6c75a799bd3aa38 /lib/Config.pm6 |
Initial commit
Diffstat (limited to 'lib/Config.pm6')
-rw-r--r-- | lib/Config.pm6 | 118 |
1 files changed, 118 insertions, 0 deletions
diff --git a/lib/Config.pm6 b/lib/Config.pm6 new file mode 100644 index 0000000..f7abe4e --- /dev/null +++ b/lib/Config.pm6 @@ -0,0 +1,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(".") { + return $default unless defined($index{$_}); + + $index = $index{$_}; + } + + $index; + } + + method has(Str $key) { + my $index = $!content; + + for $key.split(".") { + return False unless defined($index{$_}); + + $index = $index{$_}; + } + + True; + } + + method set(Str $key, Any $value) + { + my $index := $!content; + + for $key.split(".") { + $index{$_} = {} unless defined($index{$_}); + + $index := $index{$_}; + } + + $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; + } +} |