Merge pull request #1782 from bburnichon/improvement/batch-load-captions

Batch load caption
This commit is contained in:
Benoît Burnichon
2016-04-01 15:55:43 +02:00
14 changed files with 848 additions and 244 deletions

View File

@@ -0,0 +1,22 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2016 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Databox;
interface DataboxBoundRepositoryFactory
{
/**
* Creates a Repository bounded to given Databox
*
* @param $databoxId
* @return object
*/
public function createRepositoryFor($databoxId);
}

View File

@@ -0,0 +1,44 @@
<?php
/**
* This file is part of Phraseanet
*
* (c) 2005-2016 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Databox;
class DataboxBoundRepositoryProvider
{
/**
* Repositories indexed by databox id
*
* @var object[]
*/
private $repositories = [];
/**
* @var DataboxBoundRepositoryFactory
*/
private $factory;
public function __construct(DataboxBoundRepositoryFactory $factory)
{
$this->factory = $factory;
}
/**
* @param int $databoxId
* @return object
*/
public function getRepositoryForDatabox($databoxId)
{
if (!isset($this->repositories[$databoxId])) {
$this->repositories[$databoxId] = $this->factory->createRepositoryFor($databoxId);
}
return $this->repositories[$databoxId];
}
}

View File

@@ -0,0 +1,31 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2016 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Hydration;
interface Hydrator
{
/**
* Hydrate an instance with provided data
*
* @param object $instance
* @param array $data
* @return void
*/
public function hydrate($instance, array $data);
/**
* Extracts data from an instance
*
* @param object $instance
* @return array
*/
public function extract($instance);
}

View File

@@ -0,0 +1,114 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2016 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Hydration;
use Assert\Assertion;
class IdentityMap implements \ArrayAccess, \IteratorAggregate, \Countable
{
/**
* @var object[]
*/
private $entities;
/**
* @var Hydrator
*/
private $hydrator;
/**
* @var object
*/
private $prototype;
/**
* @param Hydrator $hydrator
* @param object $prototype A clonable prototype of objects in idMap
*/
public function __construct(Hydrator $hydrator, $prototype)
{
$this->hydrator = $hydrator;
$this->prototype = $prototype;
}
/**
* @param string|int $index
* @param array $data
* @return object
*/
public function hydrate($index, array $data)
{
if (!isset($this->entities[$index])) {
$this->entities[$index] = clone $this->prototype;
}
$instance = $this->entities[$index];
$this->hydrator->hydrate($instance, $data);
return $instance;
}
/**
* @param array[] $data
* @return object[]
*/
public function hydrateAll(array $data)
{
Assertion::allIsArray($data);
$instances = [];
foreach ($data as $index => $item) {
$instances[$index] = $this->hydrate($index, $item);
}
return $instances;
}
public function clear()
{
$this->entities = [];
}
public function getIterator()
{
return new \ArrayIterator($this->entities);
}
public function offsetExists($offset)
{
return isset($this->entities[$offset]);
}
public function offsetGet($offset)
{
return $this->entities[$offset];
}
public function offsetSet($offset, $value)
{
Assertion::notNull($offset);
Assertion::isArray($value);
$this->hydrate($offset, $value);
}
public function offsetUnset($offset)
{
unset($this->entities[$offset]);
}
public function count()
{
return count($this->entities);
}
}

View File

@@ -0,0 +1,130 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2016 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Hydration;
use Assert\Assertion;
class ReflectionHydrator implements Hydrator
{
/**
* @var string
*/
private $className;
/**
* @var string[]
*/
private $properties;
/**
* @var null|\ReflectionClass
*/
private $reflectionClass;
/**
* @var null|\ReflectionProperty[]
*/
private $reflectionProperties;
/**
* @param string $className
* @param string[] $properties
*/
public function __construct($className, array $properties)
{
$this->className = $className;
$this->properties = $properties;
}
/**
* @param array $data
* @param object $instance
* @throws \Assert\AssertionFailedException
*/
public function hydrate($instance, array $data)
{
Assertion::isInstanceOf($instance, $this->className);
foreach ($data as $key => $value) {
$this->getReflectionProperty($key)->setValue($instance, $value);
}
}
/**
* @param object $instance
* @return array
* @throws \Assert\AssertionFailedException
*/
public function extract($instance)
{
Assertion::isInstanceOf($instance, $this->className);
$data = [];
foreach ($this->getReflectionProperties() as $name => $property) {
$data[$name] = $property->getValue($instance);
}
return $data;
}
/**
* @return \ReflectionClass
*/
private function getReflectionClass()
{
if (null === $this->reflectionClass) {
$this->reflectionClass = new \ReflectionClass($this->className);
}
return $this->reflectionClass;
}
/**
* @param string $name
* @return \ReflectionProperty
* @throws \RuntimeException
*/
private function getReflectionProperty($name)
{
$this->loadReflectionProperties();
return $this->reflectionProperties[$name];
}
/**
* @return \ReflectionProperty[]
*/
private function getReflectionProperties()
{
$this->loadReflectionProperties();
return $this->reflectionProperties;
}
private function loadReflectionProperties()
{
if (null !== $this->reflectionProperties) {
return;
}
$class = $this->getReflectionClass();
$properties = [];
foreach ($this->properties as $name) {
$property = $class->getProperty($name);
$property->setAccessible(true);
$properties[$name] = $property;
}
$this->reflectionProperties = $properties;
}
}

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* This file is part of Phraseanet * This file is part of Phraseanet
* *
@@ -36,7 +35,6 @@ interface ControlProviderInterface
/** /**
* @return string returns the value corresponding to an id * @return string returns the value corresponding to an id
* @throws \Exception if the $id is invalid
*/ */
public function getValue($id); public function getValue($id);

View File

@@ -11,30 +11,46 @@
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Utilities\StringHelper; use Alchemy\Phrasea\Utilities\StringHelper;
use Alchemy\Phrasea\Vocabulary; use Alchemy\Phrasea\Vocabulary\ControlProvider\ControlProviderInterface;
class caption_Field_Value implements cache_cacheableInterface class caption_Field_Value implements cache_cacheableInterface
{ {
const RETRIEVE_VALUES = true; const RETRIEVE_VALUES = true;
const DONT_RETRIEVE_VALUES = false; const DONT_RETRIEVE_VALUES = false;
/** @var int */ /**
* @var int
*/
protected $id; protected $id;
/** @var string */ /**
* @var string
*/
protected $value; protected $value;
/** @var \Alchemy\Phrasea\Vocabulary\ControlProvider\ControlProviderInterface */ /**
protected $VocabularyType; * @var ControlProviderInterface|null
*/
protected $vocabularyType;
/** @var int */ /**
protected $VocabularyId; * @var mixed
*/
protected $vocabularyId;
/** @var databox_field */ /**
* @var databox_field
*/
protected $databox_field; protected $databox_field;
/** @var record_adapter */ /**
* @var record_adapter
*/
protected $record; protected $record;
/**
* @var Application
*/
protected $app; protected $app;
/** /**
@@ -45,21 +61,20 @@ class caption_Field_Value implements cache_cacheableInterface
*/ */
protected $qjs; protected $qjs;
/* /**
* Tells whether the value is matched against a thesaurus value. * Tells whether the value is matched against a thesaurus value.
* @var bool
*/ */
protected $isThesaurusValue; protected $isThesaurusValue;
protected static $localCache = []; protected static $localCache = [];
/** /**
*
* @param Application $app * @param Application $app
* @param databox_field $databox_field * @param databox_field $databox_field
* @param record_adapter $record * @param record_adapter $record
* @param mixed $id * @param mixed $id
* @param bool $retrieveValues * @param bool $retrieveValues
* @return \caption_Field_Value
*/ */
public function __construct(Application $app, databox_field $databox_field, record_adapter $record, $id, $retrieveValues = self::RETRIEVE_VALUES) public function __construct(Application $app, databox_field $databox_field, record_adapter $record, $id, $retrieveValues = self::RETRIEVE_VALUES)
{ {
@@ -68,107 +83,94 @@ class caption_Field_Value implements cache_cacheableInterface
$this->record = $record; $this->record = $record;
$this->app = $app; $this->app = $app;
if($retrieveValues == self::RETRIEVE_VALUES) { if ($retrieveValues === self::RETRIEVE_VALUES) {
$this->retrieveValues(); $this->retrieveValues();
} }
} }
/**
* @return string
*/
public function getQjs() public function getQjs()
{ {
return $this->qjs; return $this->qjs;
} }
public function injectValues($value, $VocabularyType, $VocabularyId) /**
* @param string $value
* @param string $vocabularyType
* @param string $vocabularyId
*/
public function injectValues($value, $vocabularyType, $vocabularyId)
{ {
$this->value = StringHelper::crlfNormalize($value); $this->value = StringHelper::crlfNormalize($value);
try { $this->fetchVocabulary($vocabularyType, $vocabularyId);
$this->VocabularyType = $VocabularyType ? Vocabulary\Controller::get($this->app, $VocabularyType) : null;
$this->VocabularyId = $VocabularyId;
} catch (\InvalidArgumentException $e) {
} if ($this->vocabularyType) {
if ($this->VocabularyType) {
/**
* Vocabulary Control has been deactivated
*/
if (!$this->databox_field->getVocabularyControl()) { if (!$this->databox_field->getVocabularyControl()) {
// Vocabulary Control has been deactivated
$this->removeVocabulary(); $this->removeVocabulary();
} } elseif ($this->databox_field->getVocabularyControl()->getType() !== $this->vocabularyType->getType()) {
/** // Vocabulary Control has changed
* Vocabulary Control has changed
*/
elseif ($this->databox_field->getVocabularyControl()->getType() !== $this->VocabularyType->getType()) {
$this->removeVocabulary(); $this->removeVocabulary();
} } elseif (!$this->vocabularyType->validate($this->vocabularyId)) {
/** // Current Id is not available anymore
* Current Id is not available anymore
*/
elseif ( ! $this->VocabularyType->validate($this->VocabularyId)) {
$this->removeVocabulary(); $this->removeVocabulary();
} } elseif ($this->vocabularyType->getValue($this->vocabularyId) !== $this->value) {
/** // String equivalence has changed
* String equivalence has changed $this->set_value($this->vocabularyType->getValue($this->vocabularyId));
*/
elseif ($this->VocabularyType->getValue($this->VocabularyId) !== $this->value) {
$this->set_value($this->VocabularyType->getValue($this->VocabularyId));
} }
} }
$datas = [
'value' => $this->value,
'vocabularyId' => $this->VocabularyId,
'vocabularyType' => $this->VocabularyType ? $this->VocabularyType->getType() : null,
];
$this->set_data_to_cache($datas);
} }
protected function retrieveValues() protected function retrieveValues()
{ {
try { try {
$datas = $this->get_data_from_cache(); $data = $this->get_data_from_cache();
$cacheRefreshNeeded = false;
$this->value = $datas['value'];
$this->VocabularyType = $datas['vocabularyType'] ? Vocabulary\Controller::get($this->app, $datas['vocabularyType']) : null;
$this->VocabularyId = $datas['vocabularyId'];
return $this;
} catch (\Exception $e) { } catch (\Exception $e) {
$data = $this->databox_field->get_databox()->get_connection()
->fetchAssoc(
'SELECT value, VocabularyType as vocabularyType, VocabularyId as vocabularyId FROM metadatas WHERE id = :id',
[':id' => $this->id]
);
if (!is_array($data)) {
$data = [
'value' => null,
'vocabularyId' => null,
'vocabularyType' => null,
];
} }
$connbas = $this->databox_field->get_databox()->get_connection(); $cacheRefreshNeeded = true;
$sql = 'SELECT record_id, value, VocabularyType, VocabularyId FROM metadatas WHERE id = :id';
$stmt = $connbas->prepare($sql);
$stmt->execute([':id' => $this->id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if($row) {
$this->injectValues($row['value'], $row['VocabularyType'], $row['VocabularyId']);
} }
else {
$this->injectValues(null, null, null); $this->injectValues($data['value'], $data['vocabularyType'], $data['vocabularyId']);
if ($cacheRefreshNeeded) {
$this->set_data_to_cache([
'value' => $this->value,
'vocabularyId' => $this->vocabularyId,
'vocabularyType' => $this->vocabularyType ? $this->vocabularyType->getType() : null,
]);
} }
return $this; return $this;
} }
/** /**
* @return Vocabulary\ControlProvider\ControlProviderInterface * @return ControlProviderInterface|null
*/ */
public function getVocabularyType() public function getVocabularyType()
{ {
return $this->VocabularyType; return $this->vocabularyType;
} }
public function getVocabularyId() public function getVocabularyId()
{ {
return $this->VocabularyId; return $this->vocabularyId;
} }
public function getId() public function getId()
@@ -183,7 +185,7 @@ class caption_Field_Value implements cache_cacheableInterface
public function getResource() public function getResource()
{ {
return $this->VocabularyType ? $this->VocabularyType->getResource($this->VocabularyId) : null; return $this->vocabularyType ? $this->vocabularyType->getResource($this->vocabularyId) : null;
} }
public function getDatabox_field() public function getDatabox_field()
@@ -198,12 +200,7 @@ class caption_Field_Value implements cache_cacheableInterface
public function delete() public function delete()
{ {
$connbas = $this->databox_field->get_connection(); $this->getConnection()->delete('metadatas', ['id' => $this->id]);
$sql = 'DELETE FROM metadatas WHERE id = :id';
$stmt = $connbas->prepare($sql);
$stmt->execute([':id' => $this->id]);
$stmt->closeCursor();
$this->delete_data_from_cache(); $this->delete_data_from_cache();
$this->databox_field->delete_data_from_cache(); $this->databox_field->delete_data_from_cache();
@@ -213,144 +210,129 @@ class caption_Field_Value implements cache_cacheableInterface
return $this; return $this;
} }
/**
* @return $this
* @throws \Doctrine\DBAL\DBALException
*/
public function removeVocabulary() public function removeVocabulary()
{ {
$connbas = $this->databox_field->get_connection(); $this->getConnection()->executeUpdate(
'UPDATE metadatas SET VocabularyType = NULL, VocabularyId = NULL WHERE id = :meta_id',
['meta_id' => $this->getId()]
);
$params = [ $this->vocabularyId = null;
':VocabType' => null $this->vocabularyType = null;
, ':VocabularyId' => null
, ':meta_id' => $this->getId()
];
$sql_up = 'UPDATE metadatas'
. ' SET VocabularyType = :VocabType, VocabularyId = :VocabularyId'
. ' WHERE id = :meta_id';
$stmt_up = $connbas->prepare($sql_up);
$stmt_up->execute($params);
$stmt_up->closeCursor();
$this->VocabularyId = $this->VocabularyType = null;
$this->delete_data_from_cache(); $this->delete_data_from_cache();
return $this; return $this;
} }
public function setVocab(Vocabulary\ControlProvider\ControlProviderInterface $vocabulary, $vocab_id) /**
* @param ControlProviderInterface $vocabulary
* @param mixed $vocab_id
* @return $this
* @throws \Doctrine\DBAL\DBALException
*/
public function setVocab(ControlProviderInterface $vocabulary, $vocab_id)
{ {
$connbas = $this->databox_field->get_connection(); $this->getConnection()->executeUpdate(
'UPDATE metadatas SET VocabularyType = :VocabType, VocabularyId = :VocabularyId WHERE id = :meta_id',
$params = [ [
':VocabType' => $vocabulary->getType() 'VocabType' => $vocabulary->getType(),
, ':VocabularyId' => $vocab_id 'VocabularyId' => $vocab_id,
, ':meta_id' => $this->getId() 'meta_id' => $this->getId(),
]; ]
);
$sql_up = 'UPDATE metadatas'
. ' SET VocabularyType = :VocabType, VocabularyId = :VocabularyId'
. ' WHERE id = :meta_id';
$stmt_up = $connbas->prepare($sql_up);
$stmt_up->execute($params);
$stmt_up->closeCursor();
$this->set_value($vocabulary->getValue($vocab_id)); $this->set_value($vocabulary->getValue($vocab_id));
return $this; return $this;
} }
/**
* @param ControlProviderInterface|null $vocabulary
* @param mixed|null $vocabularyId
* @return $this
* @throws \Doctrine\DBAL\DBALException
*/
public function changeVocabulary(ControlProviderInterface $vocabulary = null, $vocabularyId = null)
{
if (isset($vocabulary, $vocabularyId)) {
return $this->setVocab($vocabulary, $vocabularyId);
}
return $this->removeVocabulary();
}
/**
* @param string $value
* @return $this
* @throws \Doctrine\DBAL\DBALException
*/
public function set_value($value) public function set_value($value)
{ {
$this->value = $value; $this->value = $value;
$connbas = $this->databox_field->get_connection(); $this->getConnection()->executeUpdate(
'UPDATE metadatas SET value = :value WHERE id = :meta_id',
$params = [ [
':meta_id' => $this->id 'meta_id' => $this->id,
, ':value' => $value 'value' => $value,
]; ]
);
$sql_up = 'UPDATE metadatas SET value = :value WHERE id = :meta_id';
$stmt_up = $connbas->prepare($sql_up);
$stmt_up->execute($params);
$stmt_up->closeCursor();
$this->delete_data_from_cache(); $this->delete_data_from_cache();
$this->update_cache_value($value);
return $this; return $this;
} }
/** public static function create(Application $app, databox_field $databox_field, \record_adapter $record, $value, ControlProviderInterface $vocabulary = null, $vocabularyId = null)
*
* @param array $value
* @return caption_field
*/
public function update_cache_value($value)
{ {
$this->record->get_caption()->delete_data_from_cache(); $connection = $databox_field->get_connection();
return $this; // Check consistency
}
public static function create(Application $app, databox_field $databox_field, \record_adapter $record, $value, Vocabulary\ControlProvider\ControlProviderInterface $vocabulary = null, $vocabularyId = null)
{
$connbas = $databox_field->get_connection();
/**
* Check consistency
*/
if (!$databox_field->is_multi()) { if (!$databox_field->is_multi()) {
try { try {
$field = $record->get_caption()->get_field($databox_field->get_name()); $field = $record->get_caption()->get_field($databox_field->get_name());
$values = $field->get_values(); $values = $field->get_values();
$caption_field_value = array_pop($values); } catch (Exception $exception) {
/* @var $value \caption_Field_Value */ // Field was not found, so no values found either
$caption_field_value->set_value($value); $values = [];
if (! $vocabulary || ! $vocabularyId) {
$caption_field_value->removeVocabulary();
} else {
$caption_field_value->setVocab($vocabulary, $vocabularyId);
} }
if (!empty($values)) {
/** @var caption_Field_Value $caption_field_value */
$caption_field_value = reset($values);
$caption_field_value->set_value($value);
$caption_field_value->changeVocabulary($vocabulary, $vocabularyId);
return $caption_field_value; return $caption_field_value;
} catch (\Exception $e) {
} }
} }
$sql_ins = 'INSERT INTO metadatas (id, record_id, meta_struct_id, value, VocabularyType, VocabularyId)' $data = [
. ' VALUES (null, :record_id, :field, :value, :VocabType, :VocabId)'; 'record_id' => $record->getRecordId(),
'meta_struct_id' => $databox_field->get_id(),
$params = [ 'value' => $value,
':record_id' => $record->getRecordId(), 'VocabularyType' => $vocabulary ? $vocabulary->getType() : null,
':field' => $databox_field->get_id(), 'VocabularyId' => $vocabulary ? $vocabularyId : null,
':value' => $value,
':VocabType' => $vocabulary ? $vocabulary->getType() : null,
':VocabId' => $vocabulary ? $vocabularyId : null,
]; ];
$stmt_ins = $connbas->prepare($sql_ins); $connection->insert('metadatas', $data);
$stmt_ins->execute($params);
$stmt_ins->closeCursor(); $meta_id = $connection->lastInsertId();
$meta_id = $connbas->lastInsertId();
$caption_field_value = new self($app, $databox_field, $record, $meta_id); $caption_field_value = new self($app, $databox_field, $record, $meta_id, self::DONT_RETRIEVE_VALUES);
$caption_field_value->update_cache_value($value); $caption_field_value->injectValues($data['value'], $data['VocabularyType'], $data['VocabularyId']);
$record->get_caption()->delete_data_from_cache();
$databox_field->delete_data_from_cache(); $databox_field->delete_data_from_cache();
$caption_field_value->delete_data_from_cache(); $caption_field_value->delete_data_from_cache();
return $caption_field_value; return $caption_field_value;
} }
/** /**
*
* @return string * @return string
*/ */
public function highlight_thesaurus() public function highlight_thesaurus()
@@ -390,8 +372,9 @@ class caption_Field_Value implements cache_cacheableInterface
$note = 0; $note = 0;
$note += ($node->getAttribute("lng") == $this->app['locale']) ? 4 : 0; $note += ($node->getAttribute("lng") == $this->app['locale']) ? 4 : 0;
$note += ($node->getAttribute("w") == $term_noacc) ? 2 : 0; $note += ($node->getAttribute("w") == $term_noacc) ? 2 : 0;
if($context_noacc != "") if ($context_noacc != "") {
$note += ($node->getAttribute("k") == $context_noacc) ? 1 : 0; $note += ($node->getAttribute("k") == $context_noacc) ? 1 : 0;
}
if ($note > $bestnote) { if ($note > $bestnote) {
$bestnode = $node; $bestnode = $node;
} }
@@ -407,16 +390,16 @@ class caption_Field_Value implements cache_cacheableInterface
$this->isThesaurusValue = false; $this->isThesaurusValue = false;
} }
return $this; return $this->value;
} }
/** /**
* @return boolean * @return bool
*/ */
public function isThesaurusValue() public function isThesaurusValue()
{ {
if (null === $this->isThesaurusValue) { if (null === $this->isThesaurusValue) {
$this->highlight_thesaurus(); throw new LogicException('Value was not checked against thesaurus yet. Call hightlight_thesaurus() first');
} }
return $this->isThesaurusValue; return $this->isThesaurusValue;
@@ -486,14 +469,9 @@ class caption_Field_Value implements cache_cacheableInterface
*/ */
public function delete_data_from_cache($option = null) public function delete_data_from_cache($option = null)
{ {
$this->value = $this->VocabularyId = $this->VocabularyType = null; $this->value = $this->vocabularyId = $this->vocabularyType = null;
$this->record->delete_data_from_cache(record_adapter::CACHE_TITLE); $this->record->delete_data_from_cache(record_adapter::CACHE_TITLE);
$this->record->get_caption()->delete_data_from_cache();
try {
$this->record->get_caption()->get_field($this->databox_field->get_name())->delete_data_from_cache();
} catch (\Exception $e) {
}
unset(self::$localCache[$this->get_cache_key($option)]); unset(self::$localCache[$this->get_cache_key($option)]);
} }
@@ -507,4 +485,26 @@ class caption_Field_Value implements cache_cacheableInterface
{ {
self::$localCache = []; self::$localCache = [];
} }
/**
* @param string $vocabularyType
* @param mixed $vocabularyId
*/
private function fetchVocabulary($vocabularyType, $vocabularyId)
{
try {
$this->vocabularyType = $vocabularyType ? $this->app['vocabularies'][strtolower($vocabularyType)] : null;
$this->vocabularyId = $vocabularyId;
} catch (\InvalidArgumentException $e) {
// Invalid or unknown Vocabulary
}
}
/**
* @return \Doctrine\DBAL\Connection
*/
private function getConnection()
{
return $this->databox_field->get_connection();
}
} }

View File

@@ -40,8 +40,6 @@ class caption_field implements cache_cacheableInterface
* @param databox_field $databox_field * @param databox_field $databox_field
* @param record_adapter $record * @param record_adapter $record
* @param bool $retrieveValues * @param bool $retrieveValues
*
* @return caption_field
*/ */
public function __construct(Application $app, databox_field $databox_field, \record_adapter $record, $retrieveValues = self::RETRIEVE_VALUES) public function __construct(Application $app, databox_field $databox_field, \record_adapter $record, $retrieveValues = self::RETRIEVE_VALUES)
{ {
@@ -62,8 +60,6 @@ class caption_field implements cache_cacheableInterface
} }
} }
} }
return $this;
} }
/** /**
@@ -147,27 +143,27 @@ class caption_field implements cache_cacheableInterface
} }
/** /**
* @param array $values * @param caption_Field_Value[] $values
* @param string $separator * @param string $separator
* @param bool $highlight
* @return string * @return string
*/ */
protected static function serialize_value(Array $values, $separator, $highlight = false) protected function serialize_value(array $values, $separator, $highlight = false)
{ {
if (strlen($separator) > 1) if (strlen($separator) > 1) {
$separator = $separator[0]; $separator = $separator[0];
}
if (trim($separator) === '') if (trim($separator) === '') {
$separator = ' '; $separator = ' ';
else } else {
$separator = ' ' . $separator . ' '; $separator = ' ' . $separator . ' ';
}
$array_values = []; $array_values = [];
foreach ($values as $value) { foreach ($values as $value) {
if ($highlight) $array_values[] = $highlight ? $value->highlight_thesaurus() : $value->getValue();
$array_values[] = $value->highlight_thesaurus();
else
$array_values[] = $value->getValue();
} }
return implode($separator, $array_values); return implode($separator, $array_values);
@@ -191,10 +187,10 @@ class caption_field implements cache_cacheableInterface
} }
/** /**
* @param String $custom_separator * @param string|bool $custom_separator
* @param Boolean $highlightTheso * @param bool $highlight
* *
* @return mixed * @return string
*/ */
public function get_serialized_values($custom_separator = false, $highlight = false) public function get_serialized_values($custom_separator = false, $highlight = false)
{ {
@@ -205,12 +201,12 @@ class caption_field implements cache_cacheableInterface
if ($this->is_multi()) { if ($this->is_multi()) {
$separator = $custom_separator !== false ? $custom_separator : $this->databox_field->get_separator(); $separator = $custom_separator !== false ? $custom_separator : $this->databox_field->get_separator();
return self::serialize_value($this->values, $separator, $highlight); return $this->serialize_value($this->values, $separator, $highlight);
} }
/** @var caption_Field_Value $value */
$value = current($this->values); $value = current($this->values);
/* @var $value Caption_Field_Value */
if ($highlight) { if ($highlight) {
return $value->highlight_thesaurus(); return $value->highlight_thesaurus();
} }
@@ -258,7 +254,6 @@ class caption_field implements cache_cacheableInterface
*/ */
public static function get_multi_values($serialized_value, $separator) public static function get_multi_values($serialized_value, $separator)
{ {
$values = [];
if (strlen($separator) == 1) { if (strlen($separator) == 1) {
$values = explode($separator, $serialized_value); $values = explode($separator, $serialized_value);
} else { } else {
@@ -360,8 +355,7 @@ class caption_field implements cache_cacheableInterface
$caption_field->delete(); $caption_field->delete();
$record->set_metadatas([]); $record->set_metadatas([]);
unset($caption_field); unset($caption_field, $record);
unset($record);
} catch (\Exception $e) { } catch (\Exception $e) {
} }
@@ -389,6 +383,7 @@ class caption_field implements cache_cacheableInterface
* *
* @param string $option * @param string $option
* @return mixed * @return mixed
* @throws Exception
*/ */
public function get_data_from_cache($option = null) public function get_data_from_cache($option = null)
{ {

View File

@@ -224,9 +224,14 @@ SQL;
foreach ($field->get_values() as $metaId => $v) { foreach ($field->get_values() as $metaId => $v) {
$values[$metaId] = [ $values[$metaId] = [
'value' => $v->getValue(), 'value' => $v->getValue(),
'from_thesaurus' => $highlight ? $v->isThesaurusValue() : false, 'from_thesaurus' => false,
'qjs' => $v->getQjs(), 'qjs' => null,
]; ];
if ($highlight) {
$v->highlight_thesaurus();
$values[$metaId]['from_thesaurus'] = $v->isThesaurusValue();
$values[$metaId]['qjs'] = $v->getQjs();
}
} }
$fields[$field->get_name()] = [ $fields[$field->get_name()] = [
'values' => $values, 'values' => $values,

View File

@@ -1,5 +1,4 @@
<?php <?php
/* /*
* This file is part of Phraseanet * This file is part of Phraseanet
* *
@@ -13,15 +12,17 @@ use Assert\Assertion;
class databox_descriptionStructure implements IteratorAggregate, Countable class databox_descriptionStructure implements IteratorAggregate, Countable
{ {
/** @var databox_field[] */ /**
* @var databox_field[]
*/
protected $elements = []; protected $elements = [];
/** /**
* Cache array for the get element by name function * Cache array for the get element by name function
* *
* @var array<string,int> * @var array<string,int>|null
*/ */
protected $cache_name_id = []; protected $cache_name_id;
/** /**
* @param databox_field[] $fields * @param databox_field[] $fields
@@ -51,6 +52,10 @@ class databox_descriptionStructure implements IteratorAggregate, Countable
{ {
$this->elements[$field->get_id()] = $field; $this->elements[$field->get_id()] = $field;
if (null !== $this->cache_name_id) {
$this->cache_name_id[$field->get_name()] = $field->get_id();
}
return $this; return $this;
} }
@@ -60,8 +65,9 @@ class databox_descriptionStructure implements IteratorAggregate, Countable
*/ */
public function remove_element(databox_field $field) public function remove_element(databox_field $field)
{ {
if (isset($this->elements[$field->get_id()])) if (isset($this->elements[$field->get_id()])) {
unset($this->elements[$field->get_id()]); unset($this->elements[$field->get_id()], $this->cache_name_id[$field->get_name()]);
}
return $this; return $this;
} }
@@ -75,14 +81,14 @@ class databox_descriptionStructure implements IteratorAggregate, Countable
} }
/** /**
*
* @param int $id * @param int $id
* @return databox_field * @return databox_field
*/ */
public function get_element($id) public function get_element($id)
{ {
if ( ! isset($this->elements[$id])) if (!isset($this->elements[$id])) {
throw new Exception_Databox_FieldNotFound (); throw new Exception_Databox_FieldNotFound ();
}
return $this->elements[$id]; return $this->elements[$id];
} }
@@ -93,23 +99,25 @@ class databox_descriptionStructure implements IteratorAggregate, Countable
*/ */
public function get_element_by_name($name) public function get_element_by_name($name)
{ {
$name = databox_field::generateName($name); if (null === $this->cache_name_id) {
$this->cache_name_id = [];
if (isset($this->cache_name_id[$name])) {
return $this->elements[$this->cache_name_id[$name]];
}
foreach ($this->elements as $id => $meta) { foreach ($this->elements as $id => $meta) {
if ($meta->get_name() === $name) { $this->cache_name_id[$meta->get_name()] = $id;
$this->cache_name_id[$name] = $id;
return $meta;
} }
} }
return null; $name = databox_field::generateName($name);
return isset($this->cache_name_id[$name])
? $this->elements[$this->cache_name_id[$name]]
: null;
} }
/**
* @param string $label
* @return databox_field|null
*/
public function get_dces_field($label) public function get_dces_field($label)
{ {
foreach ($this->elements as $field) { foreach ($this->elements as $field) {
@@ -125,13 +133,16 @@ class databox_descriptionStructure implements IteratorAggregate, Countable
/** /**
* @param string $id * @param string $id
* @return boolean * @return bool
*/ */
public function isset_element($id) public function isset_element($id)
{ {
return isset($this->elements[$id]); return isset($this->elements[$id]);
} }
/**
* @return array
*/
public function toArray() public function toArray()
{ {
return array_map(function (databox_field $element) { return array_map(function (databox_field $element) {

View File

@@ -16,12 +16,24 @@ class LinkedinTest extends ProviderTestCase
{ {
$state = md5(mt_rand()); $state = md5(mt_rand());
// test cases
$data = [];
$data[] = [$this->getProvider(), $this->getRequestMock()];
// Second test
$request = $this->getRequestMock(); $request = $this->getRequestMock();
$this->addQueryParameter($request, ['state' => $state]); $this->addQueryParameter($request, ['state' => $state]);
$provider1 = $this->getProvider(); $provider = $this->getProvider();
$provider1->setGuzzleClient($this->getGuzzleMock(401)); $provider->setGuzzleClient($this->getGuzzleMock(401));
$provider1->getSession()->set('linkedin.provider.state', $state); $provider->getSession()->set('linkedin.provider.state', $state);
$data[] = [$provider, $request];
// Third test
$request = $this->getRequestMock();
$this->addQueryParameter($request, ['state' => $state]);
$mock = $this->getMock('Guzzle\Http\ClientInterface'); $mock = $this->getMock('Guzzle\Http\ClientInterface');
@@ -67,15 +79,13 @@ class LinkedinTest extends ProviderTestCase
->method('post') ->method('post')
->will($this->returnValue($requestPost)); ->will($this->returnValue($requestPost));
$provider2 = $this->getProvider(); $provider = $this->getProvider();
$provider2->setGuzzleClient($mock); $provider->setGuzzleClient($mock);
$provider2->getSession()->set('linkedin.provider.state', $state); $provider->getSession()->set('linkedin.provider.state', $state);
return [ $data[] = [$provider, $request];
[$this->getProvider(), $this->getRequestMock()],
[$provider1, $request], return $data;
[$provider2, $request],
];
} }
public function getProviderForLogout() public function getProviderForLogout()

View File

@@ -0,0 +1,57 @@
<?php
/**
* This file is part of Phraseanet
*
* (c) 2005-2016 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Tests\Phrasea\Databox;
use Alchemy\Phrasea\Databox\DataboxBoundRepositoryFactory;
use Alchemy\Phrasea\Databox\DataboxBoundRepositoryProvider;
use Prophecy\Argument;
class DataboxBoundRepositoryProviderTest extends \PHPUnit_Framework_TestCase
{
/**
* @var DataboxBoundRepositoryProvider
*/
private $sut;
protected function setUp()
{
$factory = $this->prophesize(DataboxBoundRepositoryFactory::class);
$factory
->createRepositoryFor(Argument::type('integer'))
->will(function ($args) {
return (object)['databoxId' => $args[0]];
});
$this->sut = new DataboxBoundRepositoryProvider($factory->reveal());
}
public function testItCreatesRepositoriesIfUnknown()
{
$repository = $this->sut->getRepositoryForDatabox(42);
$this->assertNotNull($repository, 'Failed to create a repository');
$this->assertSame($repository, $this->sut->getRepositoryForDatabox(42));
}
public function testItShouldNotCreateTwoRepositoriesPerDatabox()
{
$repository1 = $this->sut->getRepositoryForDatabox(1);
$repository2 = $this->sut->getRepositoryForDatabox(2);
$this->assertNotNull($repository1, 'Failed to create first repository');
$this->assertNotNull($repository2, 'Failed to create second repository');
$this->assertNotSame($repository1, $repository2, 'Different Databoxes should have different repositories');
$this->assertSame($repository2, $this->sut->getRepositoryForDatabox(2), 'Second Repository should be returned');
$this->assertSame($repository1, $this->sut->getRepositoryForDatabox(1), 'First Repository should be returned');
}
}

View File

@@ -0,0 +1,114 @@
<?php
/**
* This file is part of Phraseanet
*
* (c) 2005-2016 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Tests\Phrasea\Hydration;
use Alchemy\Phrasea\Hydration\Hydrator;
use Alchemy\Phrasea\Hydration\IdentityMap;
use Prophecy\Argument;
class IdentityMapTest extends \PHPUnit_Framework_TestCase
{
/**
* @var IdentityMap
*/
private $sut;
protected function setUp()
{
$hydrator = $this->prophesize(Hydrator::class);
$hydrator->extract(Argument::type(\stdClass::class))
->will(function ($args) {
return (array)$args[0];
});
$hydrator->hydrate(Argument::type(\stdClass::class), Argument::type('array'))
->will(function ($args) {
foreach ($args[1] as $property => $value) {
$args[0]->{$property} = $value;
}
});
$this->sut = new IdentityMap($hydrator->reveal(), (object)['foo' => null, 'bar' => null]);
}
public function testItShouldBeArrayAccessibleTraversableAndCountable()
{
$this->assertInstanceOf(\Traversable::class, $this->sut);
$this->assertInstanceOf(\ArrayAccess::class, $this->sut);
$this->assertInstanceOf(\Countable::class, $this->sut);
}
public function testItShouldHydrateAnInstanceWhenNotYetInMap()
{
$expected = (object)['foo' => 'foo', 'bar' => 'bar'];
$instance = $this->sut->hydrate(42, ['foo' => 'foo', 'bar' => 'bar']);
$this->assertEquals($expected, $instance, 'Invalid instance generated');
$this->assertSame($instance, $this->sut[42], 'Accessing by offset should succeed');
}
public function testItShouldReHydrateAnInstance()
{
$instance = $this->sut->hydrate(42, ['foo' => 'Foo', 'bar' => 'Bar']);
$this->assertAttributeSame('Foo', 'foo', $instance);
$this->assertAttributeSame('Bar', 'bar', $instance);
$instance2 = $this->sut->hydrate(42, ['foo' => 'new foo value', 'bar' => null]);
$this->assertAttributeSame('new foo value', 'foo', $instance);
$this->assertAttributeSame(null, 'bar', $instance);
$this->assertSame($instance, $instance2, 'Same instance was not rehydrated');
$this->assertCount(1, $this->sut);
}
public function testItsOffsetCanBeUnset()
{
$this->sut[42] = ['foo' => 'Foo', 'bar' => 'Bar'];
$this->assertTrue(isset($this->sut[42]), 'Offset should exists');
unset($this->sut[42]);
$this->assertFalse(isset($this->sut[42]), 'Offset should not exists after unset');
}
public function testItHydratesAllEntities()
{
$data = [
['foo' => 'Foo1', 'bar' => 'Bar1'],
['foo' => 'Foo2', 'bar' => 'Bar2'],
];
$this->sut->hydrateAll($data);
$entities = [];
foreach ($this->sut as $key => $value) {
$entities[$key] = $value;
}
foreach ($data as $key => $value) {
$this->assertArrayHasKey($key, $entities, 'An entity is missing');
$this->assertEquals((object)$value, $entities[$key], 'Unexpected entity value');
}
$this->assertCount(2, $this->sut);
$this->sut->clear();
$this->assertCount(0, $this->sut, 'Map was not cleared');
}
}

View File

@@ -0,0 +1,73 @@
<?php
/**
* This file is part of Phraseanet
*
* (c) 2005-2016 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Tests\Phrasea\Hydration;
use Alchemy\Phrasea\Hydration\Hydrator;
use Alchemy\Phrasea\Hydration\ReflectionHydrator;
class ReflectionHydratorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ReflectionHydrator
*/
private $sut;
protected function setUp()
{
$this->sut = new ReflectionHydrator(ToHydrate::class, ['foo', 'bar']);
}
public function testItThrowsExceptionOnUnknownProperty()
{
$this->setExpectedException(\ReflectionException::class);
$sut = new ReflectionHydrator(ToHydrate::class, ['baz']);
$sut->extract(new ToHydrate());
}
public function testItShouldImplementHydrator()
{
$this->assertInstanceOf(Hydrator::class, $this->sut);
}
public function testItShouldProperlyHydrateInstance()
{
$stub = new ToHydrate();
$this->sut->hydrate($stub, ['foo' => 'foo modified', 'bar' => 'bar changed']);
$this->assertEquals('foo modified', $stub->getFoo(), 'Property foo was not hydrated');
$this->assertEquals('bar changed', $stub->getBar(), 'Property bar was not hydrated');
}
public function testItShouldProperlyExtractData()
{
$data = $this->sut->extract(new ToHydrate());
$this->assertSame(['foo' => 'foo', 'bar' => 'bar'], $data, 'Improper extraction of properties');
}
}
class ToHydrate
{
private $foo = 'foo';
private $bar = 'bar';
public function getFoo()
{
return $this->foo;
}
public function getBar()
{
return $this->bar;
}
}