/*
|--------------------------------------------------------------------------
| Entity
|--------------------------------------------------------------------------
966205
function EntityInfo(obj) {
    const {id, states, destinStates} = obj

    this.id = id
    this.states = states
    this.destinStates = destinStates

    this.trackerWebsite = tracker.getLink(id)
}
159014
private Entity<? extends Serializable> onAfterSave(
			Entity<? extends Serializable> entity) {
		Class<?> cls = entity.getClass();
		if (Treeable.class.isAssignableFrom(cls)) {
			Treeable self = (Treeable) entity;
			if (notNull(self.getParent())) {
				Treeable parent = (Treeable) getCurrentSession().get(cls,
						self.getParent());
				self.setPath(parent.getPath() + entity.getId().toString() + "/");
				getCurrentSession().update(self);
			}
		}
		return entity;
	}
609572
public function setEntity($entity, $prepare = true)
	{
		if($entity instanceof EntityInterface)
		{
			$this->entity = $entity;
		}
		elseif(is_resource($entity) || $entity instanceof StreamInterface)
		{
			$this->entity = new StreamEntity($entity);
		}
		elseif((is_array($entity) || is_object($entity)) && is_callable($entity))
		{
			$this->entity = new CallbackEntity($entity);
		}
		else
		{
			$this->entity = new StringEntity($entity);
		}
		
		if($prepare)
		{
			$this->entity->prepare($this);
		}
		
		return $this;
	}
123954
protected function updateEntity(Entity $entity)
    {
        $action = \Schema::hasTable($entity->getTable()) ? 'update' : 'create';

        $this->migrations[$action][$entity->getTable()]['cols'] = $this->buildTable($entity);

        if($action == 'create' && $entity->timestamps) $this->migrations[$action][$entity->getTable()]['cols'][] = '$table->timestamps();';
    }
703503
public function update($entity)
    {
        $eloquentModel = $this->getEloquentModel($entity, true);

        $this->updateRelations($eloquentModel, 'update');

        $eloquentModel->save();

        $eloquentModel->afterSaving($entity, 'update');
    }
1336543
public function commit($entity)
    {
        switch ($entity->getEntityState()) {
            case AnDomain::STATE_NEW:
                $operation = AnDomain::OPERATION_INSERT;
                $command = 'insert';
                break;
            case AnDomain::STATE_MODIFIED :
                //get all the updated serializable property/value pairs
                $operation = AnDomain::OPERATION_UPDATE;
                $command = 'update';
                break;
            case  AnDomain::STATE_DELETED :
                $operation = AnDomain::OPERATION_DELETE;
                $command = 'delete';
                break;
            default :
                return;
        }

        $context = $this->getCommandContext();
        $context->operation = $operation;
        $context->entity = $entity;
        $context->data = array();
        $store = $this->getStore();

        if ($context->result = $this->getCommandChain()->run('before.'.$command, $context) !== false) {
            $context->data = $entity->getAffectedRowData();

            switch ($operation) {
                case(AnDomain::OPERATION_INSERT) :
                    if (!count($context->data)) {
                        throw new AnDomainRepositoryException('Attempting to store an entity with empty data');
                    }

                    $context->result = $store->insert($this, $context->data);
                    break;

                case(AnDomain::OPERATION_UPDATE) :
                case(AnDomain::OPERATION_DELETE) :

                    $keys = $this->_description->getIdentityProperty()->serialize($entity->getIdentityId());
                    $keys = array($this->_description->getIdentityProperty()->getName() => $entity->getIdentityId());

                    if ($operation & AnDomain::OPERATION_UPDATE) {
                        $context->result = count($context->data) ? $this->update($context->data, $keys) : true;
                    } else {
                        $context->result = $this->destroy($keys);
                    }
            }

            $this->getCommandChain()->run('after.'.$command, $context);
        }

        return    $context->result !== false;
    }
366675
function _loadEntity() {
    if (_Entity && _Entity !== models.Entity) {
      if (_nameValidation) {
        _Entity.adapter.loadEntity(_Entity);

        for (var attribute in _attributes) {
          _loadEntityAttribute(_attributes[attribute]);
        }
      }

      for (var method in _methods) {
        _loadEntityMethod(_methods[method], method);
      }
    }
  }
728241
private Entity fixEntity(Entity entity){
		if(null == entity){
			entity = Entity.create(tableName);
		}else if(StrUtil.isBlank(entity.getTableName())){
			entity.setTableName(tableName);
		}
		return entity;
	}
484570
public function setEntity(Entity $entity)
    {
        /** @var SharedEventManager $events */
        $events = $this->getContainer()->get('sharedEventManager');
        $name = $entity->getClassName();
        $events->attach(
            $name,
            Delete::BEFORE_DELETE,
            [$this, 'beforeDelete']
        );
        $events->attach(
            $name,
            Save::AFTER_SAVE,
            [$this, 'afterSave']
        );
        $this->getContainer()->set('sharedEventManager', $events);
        return parent::setEntity($entity);
    }
642714
public function delete($id)
    {
        $this->beforeDelete($id);
        $this->entity->delete($id);
        $this->afterDelete($id);
    }
98918
function onSuccess() {
            /**
             * Make sure to clear the cache for this Entity Kind
             */
            if (_this.constructor.__hasCache(options)) {
                return _this.constructor.clearCache()
                    .then(() => _this)
                    .catch((err) => {
                        let msg = 'Error while clearing the cache after saving the entity.';
                        msg += 'The entity has been saved successfully though. ';
                        msg += 'Both the cache error and the entity saved have been attached.';
                        const cacheError = new Error(msg);
                        cacheError.__entity = _this;
                        cacheError.__cacheError = err;
                        throw cacheError;
                    });
            }

            return _this;
        }
853555
private void processEntity(Entity entity, double latitude, double longitude) {
        // Only add entities that fall within the bounding box (if set)
        BoundingBox bb = this.configuration.getBboxConfiguration();
        if (bb != null && !bb.contains(latitude, longitude)) {
            return;
        }

        // Only add entities that have data
        if (entity.getTags().isEmpty()) {
            return;
        }

        // Only add named entities (if set)
        if (this.configuration.isNames()) {
            String name = getTagValue(entity.getTags(), "name");
            if (name == null || name.isEmpty()) {
                return;
            }
        }

        // Process entity
        Map<String, String> tagMap = new TreeMap<>();
        Set<PoiCategory> categories = new HashSet<>();
        for (Tag tag : entity.getTags()) {
            String key = tag.getKey().toLowerCase(Locale.ENGLISH);
            if (this.tagMappingResolver.getMappingTags().contains(key)) {
                // Check if there is a POI category for this tag and add POI to DB
                String tagStr = key + "=" + tag.getValue();
                try {
                    // Get categories from tag
                    List<PoiCategory> pcs = this.tagMappingResolver.getCategoriesFromTag(tagStr);

                    // Get categories from key, if tag wasn't matched
                    // Note: key categories should be parents of their value categories
                    if (pcs == null) {
                        pcs = this.tagMappingResolver.getCategoriesFromTag(key);
                    }

                    if (pcs != null) {
                        for (PoiCategory pc : pcs) {
                            // Add entity if its category matches
                            if (this.categoryFilter.isAcceptedCategory(pc)) {
                                // Collect the POI tags in a sorted manner (once)
                                if (tagMap.isEmpty()) {
                                    for (Tag t : entity.getTags()) {
                                        tagMap.put(t.getKey().toLowerCase(Locale.ENGLISH), t.getValue());
                                    }
                                }
                                categories.add(pc);
                            }
                        }
                    }
                } catch (UnknownPoiCategoryException e) {
                    LOGGER.warning("The '" + tagStr + "' tag refers to a POI that does not exist: " + e.getMessage());
                }
            }
        }

        // Store POI
        if (!tagMap.isEmpty()) {
            writePOI(this.poiAdded++, latitude, longitude, tagMap, categories);
        }
    }
1053440
function _processNode(node, level) {
        var nodeData = null;
        
        // entity tag
        if (w.isReadOnly === false && node.attr('_entity') && (node.attr('_tag') || node.attr('_note'))) {
            var id = node.attr('name');
            var entity = w.entitiesManager.getEntity(id);
            var type = node.attr('_type');
            var tag = node.attr('_tag');
            if (tag == null) {
                tag = w.schemaManager.mapper.getParentTag(type);
            }
            
            nodeData = {
                text: tag,
                li_attr: {name: id}, // 'class': type}
                state: {opened: level < 3}
            };
            
            if (w.schemaManager.mapper.isEntityTypeNote(type)) {
                var content = w.schemaManager.mapper.getNoteContentForEntity(entity);
                switch($.type(content)) {
                    case 'array':
                        nodeData.children = [];
                        for (var i = 0; i < content.length; i++) {
                            nodeData.children.push({
                                text: content[i],
                                li_attr: {name: id}
                            });
                        }
                        break;
                    case 'string':
                        nodeData.children = [];
                        nodeData.children.push({
                            text: content,
                            li_attr: {name: id}
                        });
                        break;
                    case 'object':
                        if (content.nodeType !== undefined) {
                            var root = $(tag, content).first();
                            
                            var processChildren = function(children, parent, id) {
                                children.each(function(index, el) {
                                    if (parent.children == null) parent.children = [];
                                    var childData = {
                                        text: el.nodeName,
                                        li_attr: {name: id}
                                    };
                                    parent.children.push(childData);
                                    
                                    processChildren($(el).children(), childData, id);
                                });
                            }
                            
                            processChildren(root.children(), nodeData, id);
                        }
                }
            }
            
        // structure tag
        } else if (node.attr('_tag')) {
            var tag = node.attr('_tag');
            if (w.isReadOnly === false || (w.isReadOnly && (tag === w.root || tree.tagFilter.indexOf(tag.toLowerCase()) !== -1))) {
                var id = node.attr('id');
                var info = w.structs[id];
                
                if (info == undefined) {
                    // redo/undo re-added a struct check
                    info = w.deletedStructs[id];
                    if (info != undefined) {
                        w.structs[id] = info;
                        delete w.deletedStructs[id];
                    }
                }
                
                if (info) {
                    var text = info._tag;
                    if (w.isReadOnly) {
                        if (tag === w.root) {
                            text = w.root;// || w.currentDocId;
                        } else {
                            text = w.utilities.getTitleFromContent(node.text());
                        }
                    }
                    nodeData = {
                        text: text,
                        li_attr: {name: id},
                        state: {opened: level < 3}
                    };
                }
            }
        }
        if (nodeData !== null) {
            nodeData.level = level;
            // FIXME we really shouldn't have this hardcoded here
            // manually set the level for CWRC schema to have proper sorting in readOnly mode
            if (w.schemaManager.schemaId === 'cwrcEntry') {
                var subtype = node.attr('subtype');
                if (subtype !== undefined) {
                    nodeData.level = parseInt(subtype);
                }
            }
        }
        
        return nodeData;
    }
5814
function(entity) {
  // Bind to start event right away.
  var boundStart = entity.start.bind(entity);
  this.on('start', boundStart);
  // Bind to preloadComplete, but only once.
  var boundPreloadComplete = entity.preloadComplete.bind(entity);
  this.once('preloadComplete', boundPreloadComplete);
  // Only bind to update after preloadComplete event.
  var boundUpdate = entity.update.bind(entity);
  this.once('preloadComplete', function() {
    this.on('update', boundUpdate);
  }.bind(this));
  entity.on('destroy', function() {
    this.removeListener('start', boundStart);
    this.removeListener('preloadComplete', boundPreloadComplete);
    this.removeListener('update', boundUpdate);
  }.bind(this));
  this.emit('entityAdded', entity);
}
540829
public function data($entity = '') {
        $entities = [];

        foreach ($this->_data as $line) {
            if ($entity != '') {
                /** @var  $entityObject \Gcs\Framework\Core\Orm\Entity\Entity */
                $entityObject = self::Entity()->$entity();

                foreach ($line as $key => $field) {
                    $value = null;
                    $parent = '';

                    $key = str_replace('count_one_' . $entityObject->name() . '_', '', $key);
                    $key = str_replace('count_many_' . $entityObject->name() . '_', '', $key);
                    $key = str_replace($entityObject->name() . '_', '', $key);

                    if ($entityObject->getField($key) != null) {
                        if (in_array($entityObject->getField($key)->type, [Field::INCREMENT, Field::INT, Field::TEXT, Field::FLOAT, Field::STRING, Field::CHAR, Field::BOOL, Field::DATE, Field::DATETIME, Field::TIMESTAMP, Field::ENUM])) {
                            if ($entityObject->getField($key)->foreign == null) {
                                //If the field is a Datetime or Date or Timestamp we must convert it to \DateTime
                                switch ($entityObject->getField($key)->type) {
                                    case Field::DATETIME:
                                        $value = new \DateTime($field);
                                        break;

                                    case Field::DATE:
                                        $value = new \DateTime($field);
                                        break;

                                    case Field::TIMESTAMP:
                                        $value = new \DateTime($field);
                                        break;

                                    default:
                                        $value = $field;
                                        break;
                                }
                            }
                            elseif (in_array($entityObject->getField($key)->foreign->type(), [ForeignKey::ONE_TO_MANY, ForeignKey::MANY_TO_MANY])) {
                                $value = $field;
                            }
                            else {
                                foreach ($entityObject->fields() as $fieldIsRightForeign) {
                                    if ($fieldIsRightForeign->foreign != null) {
                                        $parent = $fieldIsRightForeign->name . '_';
                                        $value = $this->_getDataRelation($line, $entityObject->getField(str_replace($fieldIsRightForeign->name . '_', '', $key))->foreign, $parent);
                                    }
                                }
                            }
                        }
                        else {
                            switch ($entityObject->getField($key)->type) {
                                case Field::FILE :
                                    $file = new File('', '', '', '');
                                    $file->hydrate($field);
                                    $value = $file;
                                    break;
                            }
                        }

                        $fieldName = str_replace($parent, '', $key);
                        $entityObject->set($fieldName, $value);
                    }
                }
            }
            else {
                $entityObject = new Multiple($line);
            }

            array_push($entities, $entityObject);
        }

        return new Collection($entities);
    }
1062023
function Entity(route, opts) {
  if (!(this instanceof Entity)) return new Entity(route, opts);
  this._route = route;
  this._options = opts || {};
  this._methods = {};
  this.on('error', function() { /* stifle auto exit on error */ });
}
1009336
function (entity, options, callback) {
                if (entity instanceof Entity) {
                    entity.validate(options, callback);
                } else {
                    callback("parameter is not an entity");
                }
            }