/** * Retrieve an entity by its identifier. * * @param mixed $id * @return mixed * @throws \Exception */ public function find($id) { if ($entity = $this->manager->getById($id, $this->metadata->getClass())) { return $entity; } return $this->where([$this->metadata->getIdentifier() => $id])->first(); }
/** * Map targets to entities * * @param array $entities * @param array $targets */ protected function map($entities, $targets) { $identifier = $this->targetMetadata->getIdentifier(); foreach ($targets as $target) { $id = $this->targetMetadata->getValue($target, $this->keyTo, true); foreach ($entities as $entity) { if ($id == $this->metadata->getValue($entity, $this->keyFrom, true)) { $value = $this->metadata->getValue($entity, $this->name); if (is_array($value)) { $value[$this->targetMetadata->getValue($target, $identifier)] = $target; } else { $value = $target; } $this->metadata->setValue($entity, $this->name, $value); } } } }
/** * Loads an entity or creates a new one if it does not already exist. * * @param Metadata $metadata * @param array $data * @return object */ public function load(Metadata $metadata, array $data) { $id = $data[$metadata->getIdentifier()]; $class = $metadata->getClass(); if (isset($this->entities[$class][$id])) { $entity = $this->entities[$class][$id]; } else { $entity = $metadata->newInstance(); $metadata->setValues($entity, $data, true, true); $this->identifiers[spl_object_hash($entity)] = $id; $this->entities[$class][$id] = $entity; } $this->manager->dispatchEvent(Events::postLoad, $entity, $metadata); return $entity; }
/** * Dispatches an event to all registered listeners. * * @param string $name * @param mixed $entity * @param Metadata $metadata * @return bool */ public function dispatchEvent($name, $entity, Metadata $metadata) { $prefix = $metadata->getEventPrefix(); $event = new $this->eventClass($entity, $metadata, $this); if ($events = $metadata->getEvents() and isset($events[$name])) { foreach ($events[$name] as $callback) { call_user_func_array([$entity, $callback], [$event]); } } $this->connection->getEventDispatcher()->dispatch(($prefix ? $prefix . '.' : '') . $name, $event); }