all files / src/context/ namespaces.js

90.32% Statements 28/31
80% Branches 8/10
75% Functions 3/4
93.1% Lines 27/29
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              1×           1× 1× 1× 1×                 1× 11× 11× 9×     2× 2× 2× 2× 5× 5× 5× 3× 3×   5×   2×             1× 4× 3×   1×   4×           1×         1×  
/*!
 * Copyright (C) 2017 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-transpiler/graphs/contributors
 * @url http://glayzzle.com
 */
'use strict';
 
var Namespace = require('./reflection/namespace');
 
/**
 * Handles namespaces
 * @constructor Variables
 */
var Namespaces = function() {
  this.root = new Namespace('', '', null);
  this.current = this.root;
  this.items = {
    '\\': this.root
  };
};
 
/**
 * gets or creates a namespace
 * @return {Namespace}
 */
Namespaces.prototype.get = function(name) {
  if (name[0] !== '\\') name = '\\' + name;
  if (name in this.items) {
    return this.items[name];
  }
  // build the namespace tree
  name = name.split('\\');
  var prefix = '';
  var item  = this.root;
  for(var i = 1; i < name.length; i++) {
    var child = name[i];
    prefix += '\\' + child;
    if (!(child in item.children)) {
      item.children[child] = new Namespace(child, prefix, item);
      this.items[prefix] = item.children[child];
    }
    item = item.children[child];
  }
  return item;
};
 
/**
 * Sets the current namespace
 * @return {Namespace}
 */
Namespaces.prototype.use = function(name) {
  if (!name) {
    this.current = this.root;
  } else {
    this.current = this.get(name);
  }
  return this.current;
};
 
/**
 * Checks if the namespace is defined
 */
Namespaces.prototype.has = function(name) {
  if (name[0] !== '\\') name = '\\' + name;
  return name in this.items;
};
 
module.exports = Namespaces;