ph-dev-tools
Version:
Development Tools for PHibernate
123 lines (105 loc) • 3.03 kB
text/typescript
import {EntityCandidate} from "./EntityCandidate";
import {PropertyDocEntry} from "./DocEntry";
import {endsWith} from "./utils";
/**
* Created by Papa on 3/27/2016.
*/
export class EntityCandidateRegistry {
entityCandidateMap:Map<string, EntityCandidate> = new Map<string, EntityCandidate>();
constructor(
private rootEntity:EntityCandidate
) {
}
addCandidate(
candidate:EntityCandidate
):void {
let matchesExisting = this.matchToExistingEntity(candidate);
if (!matchesExisting) {
this.entityCandidateMap.set(candidate.type, candidate);
} else {
candidate = this.entityCandidateMap.get(candidate.type);
}
if (candidate.parentKeyword === this.rootEntity.type) {
candidate.parent = this.rootEntity;
} else {
let parentEntity = this.entityCandidateMap.get(candidate.parentKeyword);
if (parentEntity) {
candidate.parent = parentEntity;
}
}
}
matchVerifiedEntities( //
targetCandidateRegistry?:EntityCandidateRegistry //
):EntityCandidate[] {
let classifiedEntities = this.classifyEntityProperties();
let classifiedEntitySet = new Set();
for (let candidate of classifiedEntities) {
classifiedEntitySet.add(candidate);
}
let matchingEntities:EntityCandidate[] = [];
for (let targetCandidate of targetCandidateRegistry.entityCandidateMap.values()) {
if (classifiedEntitySet.has(targetCandidate)) {
matchingEntities.push(targetCandidate);
}
}
return matchingEntities;
}
classifyEntityProperties():EntityCandidate[] {
let classifiedEntities:EntityCandidate[] = [];
for (let [type, candidate] of this.entityCandidateMap) {
classifiedEntities.push(candidate);
}
classifiedEntities.forEach(( //
verifiedEntity:EntityCandidate //
) => {
let properties = verifiedEntity.docEntry.properties;
if (!properties) {
return;
}
properties.forEach(( //
property:PropertyDocEntry //
) => {
let type = property.type;
if (endsWith(type, '[]')) {
property.isArray = true;
type = type.substr(0, type.length - 2);
}
switch (type) {
case 'boolean':
property.primitive = 'boolean';
return;
case 'number':
property.primitive = 'number';
return;
case 'string':
property.primitive = 'string';
return;
case 'Date':
property.primitive = 'Date';
return;
}
let foundEntity = classifiedEntities.some(( //
verifiedEntity:EntityCandidate //
) => {
if (verifiedEntity.type === type) {
property.entity = verifiedEntity;
return true;
}
});
if (!foundEntity) {
throw `Unknown Entity type: '${type}'`;
}
});
});
return classifiedEntities;
}
matchToExistingEntity(
entityCandidate:EntityCandidate
) {
let existingCandidate = this.entityCandidateMap.get(entityCandidate.type);
if (!existingCandidate) {
return false;
}
return true;
}
}