blib/lib/TBX/Min.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« blib/lib/TBX/Min/Note.pm ↑ Summary
1 #
2 # This file is part of TBX-Min
3 #
4 # This software is copyright (c) 2016 by Alan Melby.
5 #
6 # This is free software; you can redistribute it and/or modify it under
7 # the same terms as the Perl 5 programming language system itself.
8 #
9 package TBX::Min;
10 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 our $VERSION = '0.07'; # VERSION
13 # ABSTRACT: Read, write and edit TBX-Min files
14 9 ▶use subs qw(date_created directionality entries);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 9 use Class::Tiny qw(
16 id
17 description
18 creator
19 license
20 source_lang
21 target_lang
22 date_created
23 directionality
24 entries
25 9 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
26 9 ▶use XML::Twig;
Subroutine BEGIN: called CC=1 SCAR=2.6
27 use autodie;
28 use Path::Tiny;
29 use Carp;
30 use Import::Into;
31 use DateTime::Format::ISO8601;
32 use Try::Tiny;
33 use TBX::Min::TermEntry;
34 use TBX::Min::LangSet;
35 use TBX::Min::TIG;
36 use TBX::Min::NoteGrp;
37 use TBX::Min::Note;
38  
39 # Use Import::Into to export subclasses into caller
40 sub import {
41 my $target = caller;
42 TBX::Min::TermEntry->import::into($target);
43 TBX::Min::LangSet->import::into($target);
44 TBX::Min::TIG->import::into($target);
45 TBX::Min::NoteGrp->import::into($target);
46 TBX::Min::Note->import::into($target);
47 return;
48 }
49  
50 sub new_from_xml {
51 my ($class, $data) = @_;
52  
53 if(!$data){
54 croak 'missing required data argument';
55 }
56  
57 my $fh = _get_handle($data);
58  
59 # build a twig out of the input document
60 my $twig = XML::Twig->new(
61 output_encoding => 'UTF-8',
62 # do_not_chain_handlers => 1, #can be important when things get complicated
63 keep_spaces => 0,
64  
65 # these store new entries, langSets and tigs
66 start_tag_handlers => {
67 termEntry => \&_termEntryStart,
68 langSet => \&_langStart, #langset
69 tig => \&_termGrpStart, #tig
70 noteGrp => \&_noteGrpStart, #note group
71 note => \&_noteStart, #note
72 },
73  
74 TwigHandlers => {
75 TBX => \&_check_dialect,
76 # header attributes become attributes of the TBX::Min object
77 id => \&_headerAtt,
78 description => \&_headerAtt,
79 dateCreated => \&_date_created,
80 creator => \&_headerAtt,
81 license => \&_headerAtt,
82 directionality => \&_directionality,
83 languages => \&_languages,
84  
85 # becomes part of the current TBX::Min::TermEntry object
86 subjectField => sub {
87 shift->{tbx_min_entries}->[-1]->subject_field($_->text)},
88  
89 # these become attributes of the current TBX::Min::TIG object
90 term => sub {shift->{tbx_min_current_term_grp}->term($_->text)},
91 partOfSpeech => sub {
92 shift->{tbx_min_current_term_grp}->part_of_speech($_->text)},
93 customer => sub {
94 shift->{tbx_min_current_term_grp}->customer($_->text)},
95 termStatus => sub {
96 shift->{tbx_min_current_term_grp}->status($_->text)},
97  
98 # these become attributes of the current TBX::Min::Note object
99 noteKey => sub {shift->{tbx_min_current_note}->noteKey($_->text)},
100 noteValue => sub {shift->{tbx_min_current_note}->noteValue($_->text)},
101  
102 # delete the termEntry twig when finished to free up memory
103 termEntry => sub {$_[0]->purge},
104 }
105 );
106  
107 # use handlers to process individual tags, then grab the result
108 $twig->parse($fh);
109 my $self = $twig->{tbx_min_att};
110 $self->{entries} = $twig->{tbx_min_entries} || [];
111 bless $self, $class;
112 return $self;
113 }
114  
115 sub _get_handle {
116 my ($data) = @_;
117 my $fh;
118 if((ref $data) eq 'SCALAR'){
119 open $fh, '<', $data; ## no critic(RequireBriefOpen)
120 }else{
121 $fh = path($data)->filehandle('<');
122 }
123 return $fh;
124 }
125  
126  
127 my %valid = map +($_=>1), Class::Tiny->get_all_attributes_for(__PACKAGE__);
128 sub new {
129 my ($class, $args) = @_;
130 my $self;
131 if((ref $args) eq 'HASH'){
132  
133 # validate arguments
134 if(my @invalids = grep !$valid{$_}, sort keys %$args){
135 croak 'Invalid attributes for class: ' .
136 join ' ', @invalids
137 }
138 if($args->{entries} && ref $args->{entries} ne 'ARRAY'){
139 croak q{Attribute 'entries' should be an array reference};
140 }
141 if(exists $args->{directionality}){
142 _validate_dir($args->{directionality});
143 }
144  
145 # validate datetime and store object, not string
146 if(my $dt_string = $args->{date_created}){
147 $args->{date_created} = _parse_datetime($dt_string);
148 }
149  
150 $self = $args;
151 }else{
152 $self = {};
153 }
154 $self->{entries} ||= [];
155 return bless $self, $class;
156 }
157  
158 sub date_created {
159 my ($self, $date_created) = @_;
160 if($date_created) {
161 return $self->{date_created} =
162 _parse_datetime($date_created);
163 }
164 if(my $dt = $self->{date_created}){
165 return $dt->iso8601;
166 }
167 return;
168 }
169  
170 sub _parse_datetime {
171 my ($dt_string) = @_;
172 my $dt;
173 try{
174 $dt = DateTime::Format::ISO8601->parse_datetime($dt_string);
175 }catch{
176 croak 'date is not in ISO8601 format';
177 };
178 return $dt;
179 }
180  
181 sub directionality {
182 my ($self, $directionality) = @_;
183 if(defined $directionality) {
184 _validate_dir($directionality);
185 return $self->{directionality} = $directionality;
186 }
187 return $self->{directionality};
188 }
189  
190 sub _validate_dir {
191 my ($dir) = @_;
192 if($dir ne 'bidirectional' and $dir ne 'monodirectional'){
193 croak "Illegal directionality '$dir'";
194 }
195 return;
196 }
197  
198 sub entries { ## no critic(RequireArgUnpacking)
199 my ($self) = @_;
200 if (@_ > 1){
201 croak 'extra argument found (entries is a getter only)';
202 }
203 return $self->{entries};
204 }
205  
206 sub add_entry {
207 my ($self, $termEntry) = @_;
208 if( !$termEntry || !$termEntry->isa('TBX::Min::TermEntry') ){
209 croak 'argument to add_entry should be a TBx::Min::TermEntry';
210 }
211 push @{$self->{entries}}, $termEntry;
212 return;
213 }
214  
215 sub as_xml {
216 my ($self) = @_;
217  
218 # construct the whole document using XML::Twig::El's
219 my $root = XML::Twig::Elt->new(TBX => {dialect => 'TBX-Min'});
220 my $header = XML::Twig::Elt->new('header')->paste($root);
221  
222 # each of these header elements is a simple element with text
223 for my $header_att (
224 qw(id creator license directionality description)){
225 next unless $self->{$header_att};
226 XML::Twig::Elt->new($header_att,
227 $self->{$header_att})->paste(last_child => $header);
228 }
229 if($self->source_lang || $self->target_lang){
230 my @atts;
231 push @atts, (source => $self->source_lang) if $self->source_lang;
232 push @atts, (target => $self->target_lang) if $self->target_lang;
233 XML::Twig::Elt->new(languages => {@atts})->paste(
234 last_child => $header)
235 }
236 if(my $dt = $self->{date_created}){
237 XML::Twig::Elt->new(dateCreated => $dt->iso8601)->paste(
238 last_child => $header);
239 }
240  
241 my $body = XML::Twig::Elt->new('body')->paste(last_child => $root);
242 for my $termEntry (@{$self->entries}){
243 my $entry_el = XML::Twig::Elt->new(
244 termEntry => {$termEntry->id ? (id => $termEntry->id) : ()})->
245 paste(last_child => $body);
246 my $entry_el_comment = XML::Twig::Elt->new( '#COMMENT', 'terminological entry')->
247 paste(last_child => $entry_el);
248 if(my $sf = $termEntry->subject_field){
249 XML::Twig::Elt->new(subjectField => $sf)->paste(
250 last_child => $entry_el);
251 }
252 for my $langGrp (@{$termEntry->lang_groups}){
253 my $lang_el = XML::Twig::Elt->new(langSet =>
254 {$langGrp->code ? ('xml:lang' => $langGrp->code) : ()}
255 )->paste(last_child => $entry_el);
256 for my $termGrp (@{$langGrp->term_groups}){
257 my $term_el = XML::Twig::Elt->new('tig')->paste(
258 last_child => $lang_el);
259 my $term_el_comment = XML::Twig::Elt->new( '#COMMENT', 'terminological information group')->
260 paste(last_child => $term_el);
261 if (my $term = $termGrp->term){
262 XML::Twig::Elt->new(term => $term)->paste(
263 last_child => $term_el);
264 }
265  
266 if (my $customer = $termGrp->customer){
267 XML::Twig::Elt->new(customer => $customer)->paste(
268 last_child => $term_el);
269 }
270  
271 for my $noteGrp (@{$termGrp->note_groups}){
272 my $note_grp_el = XML::Twig::Elt->new('noteGrp')->paste(
273 last_child => $term_el);
274  
275 for my $note (@{$noteGrp->notes}){
276 my $note_el = XML::Twig::Elt->new('note')->paste(
277 last_child => $note_grp_el);
278  
279 if (my $noteKey = $note->noteKey){
280 XML::Twig::Elt->new(noteKey => $noteKey)->paste(
281 last_child => $note_el);
282 }
283  
284 if (my $noteValue = $note->noteValue){
285 XML::Twig::Elt->new(noteValue => $noteValue)->paste(
286 last_child => $note_el);
287 }
288  
289 }
290 }
291  
292 if (my $status = $termGrp->status){
293 XML::Twig::Elt->new(termStatus => $status )->paste(
294 last_child => $term_el);
295 }
296  
297 if (my $pos = $termGrp->part_of_speech){
298 XML::Twig::Elt->new(partOfSpeech => $pos)->paste(
299 last_child => $term_el);
300 }
301  
302 } # end tig
303 } # end langSet
304 } # end termEntry
305  
306 # return pretty-printed string
307 XML::Twig->set_pretty_print('indented');
308 my $TBXmin = \$root->sprint;
309 $$TBXmin =~ s/>[\s\t\n]*<!--/><!--/g; #force comments to be on same line as their parent
310 return $TBXmin;
311 }
312  
313 ######################
314 ### XML TWIG HANDLERS
315 ######################
316  
317 # croak if the user happened to use the wrong dialect of TBX
318 sub _check_dialect {
319 my (undef, $node) = @_;
320 my $type = $node->att('dialect') || 'unknown';
321 my $expected = 'TBX-Min';
322 if($type ne $expected){
323 croak "Input TBX is $type (should be '$expected')";
324 }
325 return 1;
326 }
327  
328 # most of the twig handlers store state on the XML::Twig object.
329 # A bit kludgy, but it works.
330  
331 sub _headerAtt {
332 my ($twig, $node) = @_;
333 $twig->{tbx_min_att}->{_decamel($node->name)} = $node->text;
334 return 1;
335 }
336  
337 sub _directionality {
338 my ($twig, $node) = @_;
339 _validate_dir($node->text);
340 $twig->{tbx_min_att}->{directionality} = $node->text;
341 return 1;
342 }
343  
344 sub _date_created {
345 my ($twig, $node) = @_;
346 $twig->{tbx_min_att}->{date_created} =
347 _parse_datetime($node->text);
348 return;
349 }
350  
351 # turn camelCase into camel_case
352 sub _decamel {
353 my ($camel) = @_;
354 $camel =~ s/([A-Z])/_\l$1/g;
355 return $camel;
356 }
357  
358 sub _languages{
359 my ($twig, $node) = @_;
360 if(my $source = $node->att('source')){
361 ${ $twig->{'tbx_min_att'} }{'source_lang'} = $source;
362 }
363 if(my $target = $node->att('target')){
364 ${ $twig->{'tbx_min_att'} }{'target_lang'} = $target;
365 }
366 return 1;
367 }
368  
369 # add a new termEntry to the list of those found in this file
370 sub _termEntryStart {
371 my ($twig, $node) = @_;
372 my $entry = TBX::Min::TermEntry->new();
373 if($node->att('id')){
374 $entry->id($node->att('id'));
375 }else{
376 carp 'found termEntry missing id attribute';
377 }
378 push @{ $twig->{tbx_min_entries} }, $entry;
379 return 1;
380 }
381  
382 #just set the subject_field of the current termEntry
383 sub _subjectField {
384 my ($twig, $node) = @_;
385 $twig->{tbx_min_entries}->[-1]->
386 subject_field($node->text);
387 return 1;
388 }
389  
390 # Create a new langSet, add it to the current termEntry,
391 # and set it as the current langSet.
392 sub _langStart {
393 my ($twig, $node) = @_;
394 my $lang = TBX::Min::LangSet->new();
395 if($node->att('xml:lang')){
396 $lang->code($node->att('xml:lang'));
397 }else{
398 carp 'found langSet missing xml:lang attribute';
399 }
400  
401 $twig->{tbx_min_entries}->[-1]->add_lang_group($lang);
402 $twig->{tbx_min_current_lang_grp} = $lang;
403 return 1;
404 }
405  
406 # Create a new tig, add it to the current langSet,
407 # and set it as the current tig.
408 sub _termGrpStart {
409 my ($twig) = @_;
410 my $term = TBX::Min::TIG->new();
411 $twig->{tbx_min_current_lang_grp}->add_term_group($term);
412 $twig->{tbx_min_current_term_grp} = $term;
413 return 1;
414 }
415  
416 # Create a new noteGrp, add it to the current tig,
417 # and set it as the curren noteGrp.
418 sub _noteGrpStart {
419 my ($twig) = @_;
420 my $note_grp = TBX::Min::NoteGrp->new();
421 $twig->{tbx_min_current_term_grp}->add_note_group($note_grp);
422 $twig->{tbx_min_current_note_grp} = $note_grp;
423 return 1;
424 }
425  
426 sub _noteStart {
427 my ($twig) = @_;
428 my $note = TBX::Min::Note->new();
429 $twig->{tbx_min_current_note_grp}->add_note($note);
430 $twig->{tbx_min_current_note} = $note;
431 return 1;
432 }
433  
434 1;
435  
436 __END__
437  
438 =pod
439  
440 =encoding UTF-8
441  
442 =head1 NAME
443  
444 TBX::Min - Read, write and edit TBX-Min files
445  
446 =head1 VERSION
447  
448 version 0.07
449  
450 =head1 SYNOPSIS
451  
452 use TBX::Min;
453 my $min = TBX::Min->new('/path/to/file.tbx');
454 my $entries = $min->entries;
455 my $termEntry = TBX::Min::TermEntry->new({id => 'B001'});
456 $min->add_entry($termEntry);
457  
458 =head1 DESCRIPTION
459  
460 This module allows you to read, write and edit the contents of TBX-Min
461 data.
462  
463 C<use>ing this module also automatically C<use>s L<TBX::Min::TermEntry>,
464 L<TBX::Min::LangSet>, and L<TBX::Min::TIG> via
465 L<Import::Into>. LangSets contain TIGs(Term Information Groups), termEntries contain
466 LangSets, and this class contains termEntries. These correspond to the
467 three levels of information found in TML. You can build up TBX::Min
468 documents this way and then print them via L</as_xml>. You can also
469 read an entire TBX-Min XML document for editing via L</new_from_xml>.
470  
471 =head1 TBX-Min
472  
473 TBX-Min is a minimal, DCT-style dialect of TBX. It's purpose is to
474 represent extremely simple termbases, such as spreadsheets, and to
475 be as human eye-friendly as possible. TBX-Min did not evolve from
476 any other XML dialect, and so does not have historical artifacts
477 such as "martif".
478  
479 DCT stands for "Data Category as Tag Name". Whereas in most TBX
480 dialects categories such as C<partOfSpeech> are indicated through
481 attributes, in TBX-Min the tag names represent categories. This
482 makes for a very readable document. While TBX-Min documents do
483 conform to TML (Terminological Markup Language) structure, DCT
484 documents cannot be checked by the
485 L<TBX-Checker|https://sourceforge.net/projects/tbxutil/>.
486  
487 If you need more complex or information-rich termbases, we suggest
488 you use TBX-Basic or even TBX-Default. If you have a TBX-Min document
489 and would like to upgrade it to TBX-Basic, see L<Convert::TBX::Min>.
490 Alternatively if you would like to change your TBX-Basic to TBX-Min,
491 see L<Convert::TBX::Basic>.
492  
493 =head1 METHODS
494  
495 =head2 C<new_from_xml>
496  
497 Creates a new instance of TBX::Min. The single argument should be either a
498 string pointer containing the TBX-Min XML data or the name of the file
499 containing this data is required.
500  
501 =head2 C<new>
502  
503 Creates a new C<TBX::Min> instance. Optionally you may pass in
504 a hash reference which is used to initialize the object. The allowed hash
505 fields are C<id>, C<description>, C<date_created>, C<creator>, C<license>,
506 C<directionality>, C<source_lang> and C<target_lang>, which correspond to
507 methods of the same name, and C<entries>, which should be an array reference
508 containing C<TBX::Min::TermEntry> objects. This method croaks if
509 C<date_created> is not in ISO 8601 format.
510  
511 =head2 C<id>
512  
513 Get or set the document id. This should be a unique string
514 identifying this glossary.
515  
516 =head2 C<description>
517  
518 Get or set the document description.
519  
520 =head2 C<date_created>
521  
522 Get or set the the date that the document was created. This should be a
523 string in ISO 8601 format. This method croaks if C<date_created> is not
524 in ISO 8601 format.
525  
526 =head2 C<creator>
527  
528 Get or set the name of the document creator.
529  
530 =head2 C<license>
531  
532 Get or set the document license string.
533  
534 =head2 C<directionality>
535  
536 Get or set the document directionality string. This string represents
537 the direction of translation this document is designed for.
538  
539 =head2 C<source_lang>
540  
541 Get or set the code representing the document source language. This should
542 be ISO 639 and 3166 (e.g. C<en-US>, C<de>, etc.).
543  
544 =head2 C<target_lang>
545  
546 Get or set the code representing the document target language. This should
547 be ISO 639 and 3166 (e.g. C<en-US>, C<de>, etc.).
548  
549 =head2 C<entries>
550  
551 Returns an array ref containing the C<TBX::Min::TermEntry> objects contained
552 in the document.The array ref is the same one used to store the objects
553 internally, so additions or removals from the array will be reflected in future
554 calls to this method.
555  
556 =head2 C<add_entry>
557  
558 Adds the input C<TBX::Min::TermEntry> object to the list of language groups
559 contained by this object.
560  
561 =head2 C<as_xml>
562  
563 Returns a scalar reference containing an XML representation of this
564 TBX-Min document. The data is a UTF-8 encoded string.
565  
566 =head1 CAVEATS
567  
568 TBX::Min does not as of yet fully validate TBX-Min documents. It is
569 possible to create non-validating XML via the L<as_xml> method.
570 This should be fixed in the future.
571  
572 =head1 SEE ALSO
573  
574 The following related modules:
575  
576 =over
577  
578 =item L<TBX::Min::TermEntry>
579  
580 =item L<TBX::Min::LangSet>
581  
582 =item L<TBX::Min::TIG>
583  
584 =item L<TBX::Min::NoteGrp>
585  
586 =item L<TBX::Min::Note>
587  
588 =item L<Convert::TBX::Min>
589  
590 =item L<Convert::TBX::Basic>
591  
592 =back
593  
594 Schema for valiating TBX-Min files are available on
595 L<GitHub|https://github.com/byutrg/TBX-Spec>.
596  
597 =head1 AUTHOR
598  
599 James Hayes <james.s.hayes@gmail.com>
600  
601 =head1 COPYRIGHT AND LICENSE
602  
603 This software is copyright (c) 2016 by Alan Melby.
604  
605 This is free software; you can redistribute it and/or modify it under
606 the same terms as the Perl 5 programming language system itself.
607  
608 =cut
« blib/lib/TBX/Min/Note.pm ↑ Summary