App-WebPerimeterScan

 view release on metacpan or  search on metacpan

lib/App/WebPerimeterScan/I18N.pm  view on Meta::CPAN


our $VERSION = '0.001.0';

# Run-time settings.  A plain hash rather than Readonly so that a caller, or
# Object::Configure, can pin a language for a whole run.
our %config = (
	# undef: take the language from the environment on every call.
	language => undef,
	# The catalogue every other language falls back to, key by key.
	fallback => 'en',
);

# Where the language comes from, most specific first.  LANGUAGE is GNU
# gettext's colon-separated preference list; the rest are POSIX.
Readonly::Array my @LOCALE_VARIABLES => qw(LANGUAGE LC_ALL LC_MESSAGES LANG);

# Locale names that mean "no preference", so they must not select a catalogue.
Readonly::Hash my %NEUTRAL_LOCALE => (C => 1, POSIX => 1);

# {name} or {name:%.1f} - the optional part is handed to sprintf.
Readonly::Scalar my $PLACEHOLDER => qr/\{(\w+)(?::(%[^{}]+))?\}/;

# The form every selector falls back to, as in ICU MessageFormat.
Readonly::Scalar my $OTHER_FORM => 'other';

# Carp's location suffix: " at FILE line N." with an optional trailing period
# and newline, and optionally ", <FH> line N." when a handle was being read.
Readonly::Scalar my $CARP_SUFFIX => qr/\s+at\s+\S.*?\s+line\s+\d+(?:,\s+<[^>]*>\s+(?:line|chunk)\s+\d+)?\.?\s*\z/s;

# Plural rules by language: count in, CLDR category out.  Only the languages
# with a catalogue need one; any other language uses the fallback's rule,
# because the words come from the fallback catalogue too.
our %PLURAL_RULE = (
	en => sub { return $_[0] == 1 ? 'one' : $OTHER_FORM },
);

=encoding utf8

=head1 NAME

App::WebPerimeterScan::I18N - message catalogue lookup and the shared error handler

=head1 VERSION

Version 0.001.0

=head1 SYNOPSIS

Render a message with values:

	use App::WebPerimeterScan::I18N;

	my $i18n = 'App::WebPerimeterScan::I18N';
	print $i18n->i18n('scope.not_listed', {
		host   => 'evil.example',
		source => 'scope.txt',
	}), "\n";

Let the count choose between singular and plural:

	# "1 endpoint defined in source was not scanned"
	# "3 endpoints defined in source were not scanned"
	print $i18n->i18n('source-routes-unvisited.title', { count => 3 }), "\n";

Choose the language, whatever the environment says:

	$App::WebPerimeterScan::I18N::config{language} = 'de';
	print $i18n->language, "\n";	# 'de' if a German catalogue exists, else 'en'

Remove the "at FILE line N." that C<croak> adds, before you show an error
to a person:

	eval { $scope->load_file('missing.txt'); 1 }
		or print App::WebPerimeterScan::I18N::clean_error($@), "\n";

Write a module that throws catalogued errors:

	package App::WebPerimeterScan::Example;

	use parent 'App::WebPerimeterScan::I18N';

	sub load
	{
		my ($self, $file) = @_;

		# croak()s with the catalogue text for the user's language
		$self->_throw('scope.empty', { file => $file }) unless -s $file;

		return $self;
	}

	# Any class or object in the distribution can render a message
	print App::WebPerimeterScan::I18N->i18n('report.summary', { summary => '0 high' }), "\n";

=head1 DESCRIPTION

Every user-facing string in the distribution - finding titles, error
messages, report labels and the command-line usage text - lives in
L<App::WebPerimeterScan::Messages> under a stable key.  This class looks the
key up for the user's language, fills in the placeholders and chooses the
plural or gender form, so no other module holds English text.

It is also the base class of every module in the distribution, which is what
gives each of them C<i18n> and the protected C<_throw> and C<_warn> helpers.
Those helpers are the only places that call C<croak> and C<carp>.

=head2 Message format

A message is either a string or a selector.

A string may contain C<{name}>, replaced by the argument of that name, or
C<{name:%.1f}>, where the part after the colon is a C<sprintf> format applied
to the argument.  A placeholder whose argument was not given is left in the
text as it is, so a missing value is visible rather than silently empty.

A selector is a hash:

	{ plural => 'count',  forms => { one => '{count} file', other => '{count} files' } }
	{ select => 'gender', forms => { female => 'her', male => 'his', other => 'their' } }

C<plural> applies the language's plural rule to the named argument to choose
the form; C<select> uses the argument's value as the form name.  Either falls

lib/App/WebPerimeterScan/I18N.pm  view on Meta::CPAN


Side Effects: none.  The environment is read on each call so a test can
change C<LC_ALL> between calls.

Usage: C<< my $lang = App::WebPerimeterScan::I18N->language; >>

=head3 EXAMPLE

	local $ENV{LC_ALL} = 'de_DE.UTF-8';
	# 'en' until a German catalogue is installed
	print App::WebPerimeterScan::I18N->language, "\n";

=head3 API SPECIFICATION

=head4 INPUT

	{}

=head4 OUTPUT

	{ type => 'string', matches => qr/\A[a-z]{2,3}\z/ }

=head3 MESSAGES

None.

=cut

sub language
{
	my ($self) = @_;

	my $catalogue = \%App::WebPerimeterScan::Messages::CATALOGUE;

	# The first preference with a catalogue wins; the fallback always exists.
	my ($chosen) = grep { exists $catalogue->{$_} } @{ _wanted_languages() };

	return $chosen // $config{fallback};
}

=head2 i18n

Purpose: return the text of a message key in the user's language, with its
placeholders filled in.

Args: C<$key> (string) and an optional hash reference of named arguments.

Returns: the rendered string.

Side Effects: C<confess>es when no catalogue - not even the fallback - holds
the key, because that is a programming error and the stack trace is what
finds it.

Usage: C<< $self->i18n('scope.empty', { file => $file }) >>

=head3 EXAMPLE

	my $text = App::WebPerimeterScan::I18N->i18n(
		'source-routes-unvisited.title', { count => 3 },
	);
	# "3 endpoints defined in source were not scanned"

=head3 API SPECIFICATION

=head4 INPUT

	{
		key  => { type => 'string', min => 1, position => 0 },
		args => { type => 'hashref', optional => 1, position => 1 },
	}

=head4 OUTPUT

	{ type => 'string' }

=head3 MESSAGES

	Message                              Meaning / resolution
	-----------------------------------  ---------------------------------------
	No message is defined for "KEY"      The key is in no catalogue.  Add it to
	                                     App::WebPerimeterScan::Messages (en).

=head3 PSEUDOCODE

	look the key up in the user's catalogue, then in the fallback
	confess if neither has it
	while the message is a selector
		choose the form named by the plural rule or the argument value
		use 'other' if that form does not exist
	replace each {name} or {name:format} that has an argument

=cut

sub i18n
{
	my ($self, $key, $args) = @_;

	# Validated by hand rather than with validate_strict: this runs for
	# every string in every report, and the two checks are all it needs.
	my $language = $self->language;
	$args = {} unless ref $args eq 'HASH';

	# A missing key is a programming error, so the full stack trace is
	# worth more than a short message.  The text itself is catalogued too.
	my $message = (defined $key && length $key) ? _lookup($language, $key) : undef;
	confess(_render(_lookup($config{fallback}, 'i18n.missing_key'), { key => $key // '' }))
		unless defined $message;

	# A selector may nest another selector (plural inside gender, say).
	$message = _select_form($language, $message, $args) while ref $message eq 'HASH';

	return _render($message, $args);
}

=head2 has_message

Purpose: say whether a key exists, for optional parts of a message family
such as a finding's C<.fix> text.

Args: C<$key> (string).



( run in 1.009 second using v1.01-cache-2.11-cpan-eb134014566 )