diff Lib/IMPL/Resources/StringLocaleMap.pm @ 378:2eed076cb944

rewritten IMPL::Resources::Strings + tests
author cin
date Wed, 15 Jan 2014 17:20:54 +0400
parents a0d342ac9a36
children a471e8b77544
line wrap: on
line diff
--- a/Lib/IMPL/Resources/StringLocaleMap.pm	Tue Jan 14 20:06:36 2014 +0400
+++ b/Lib/IMPL/Resources/StringLocaleMap.pm	Wed Jan 15 17:20:54 2014 +0400
@@ -1,6 +1,111 @@
 package IMPL::Resources::StringLocaleMap;
 use strict;
 
+use List::Util qw(first);
+use IMPL::lang qw(:base);
+use IMPL::Const qw(:prop);
+use IMPL::declare {
+	require => {
+		Resources => 'IMPL::Resources',
+		StringMap => 'IMPL::Resources::StringMap',
+		Exception => 'IMPL::Exception',
+		FS => 'File::Spec'
+	},
+	base => {
+		'IMPL::Object' => '@_'
+	},
+	props => [
+		_maps => PROP_RW,
+		name => PROP_RW,
+		paths => PROP_RW | PROP_LIST
+	]
+};
 
+sub CTOR {
+	my ($this,$data,$parent) = @_;
+	
+	if (is($data, StringMap)) {
+		$this->_maps({ default => $data });
+	} elsif ( ref($data) eq 'HASH' ) {
+		$this->_maps({ default => StringMap->new($data,$parent)});
+	}
+}
+
+sub GetString {
+	my ($this,$id,$args) = @_;
+	
+	my $locale = Resources->currentLocale || 'default';
+	my $map;
+	
+	if(not $map = $this->_maps->{$locale}) {
+		$map = $this->LoadMap($locale,$this->_maps->{default});
+		if (is($map,StringMap)) {
+			#nop
+		} elsif (ref($map) eq 'HASH') {
+			$map = StringMap->new($map,$this->_maps->{default});
+		} elsif( not $map ) {
+			$map = $this->_maps->{default};
+		} else {
+			die Exception->new("ResolveLocale returned unexpected data", $map);
+		}
+		
+		$this->_maps->{$locale} = $map;
+	}
+	
+	return $map->GetString($id,$args);
+}
+
+sub LoadMap {
+	my ($this,$locale,$default) = @_;
+	
+	my $file = first { -f } map {
+		my $name = FS->catfile($_,$locale,$this->name);
+		("$name.s", "$name.p");
+	} $this->paths;
+	
+	if($file) {
+		if ($file =~ /\.s$/) {
+			return $this->LoadStringMap($file);
+		} else {
+			return $this->LoadPerlMap($file,$default);
+		}
+	}
+	
+	return;
+}
+
+sub LoadPerlMap {
+	my ($self,$file,$parent) = @_;
+	
+	my $data = do $file;
+	my $e = $@;
+	die Exception->new("Failed to load file '$file'", $e) if $e;
+	die IOException->new("Failed to load file '$file'", $!) if not defined $data and $!;
+	die Exception->new("Failed to load file '$file'", "A hash data is expected") unless ref($data) eq 'HASH';
+	
+	return StringMap->new($data,$parent);
+}
+
+sub LoadStringMap {
+    my ($this,$fname) = @_;
+    
+    open my $hRes, "<:encoding(utf-8)", $fname or die "Failed to open file $fname: $!";
+    local $_;
+    my %map;
+    my $line = 1;
+    while (<$hRes>) {
+        chomp;
+        $line ++ and next if /^\s*$/;
+        
+        if (/^(\w+)\s*=\s*(.*)$/) {
+            $map{$1} = $2;
+        } else {
+            die "Invalid resource format in $fname at $line";
+        }
+        $line ++;
+    }
+    
+    return \%map;
+}
 
 1;
\ No newline at end of file