my changes

This commit is contained in:
Arno Kaimbacher 2018-08-06 14:30:51 +02:00
parent 28301e4312
commit 8dc1f1b048
263 changed files with 36882 additions and 4453 deletions

58
app/Library/Xml/Conf.php Normal file
View file

@ -0,0 +1,58 @@
<?php
namespace App\Library\Xml;
use App\Library\Util\Searchtypes;
use App\Dataset;
/**
* Conf short summary.
*
* Conf description.
*
* @version 1.0
* @author kaiarn
*/
class Conf
{
/**
* Holds the current model either directly set or deserialized from XML.
*
* @var Dataset
*/
public $model = null;
/**
* Holds the current DOM representation.
*
* @var \DOMDocument
*/
public $dom = null;
/**
* List of fields to skip on serialization.
*
* @var array
*/
public $excludeFields = array();
/**
* True, if empty fields get excluded from serialization.
*
* @var bool
*/
public $excludeEmpty = false;
/**
* Base URI for xlink:ref elements
*
* @var string
*/
public $baseUri = '';
/**
* Map of model class names to resource names for URI generation.
*
* @var array
*/
public $resourceNameMap = array();
}

View file

@ -0,0 +1,284 @@
<?php
namespace App\Library\Xml;
/**
* DatasetExtension short summary.
*
* DatasetExtension description.
*
* @version 1.0
* @author kaiarn
*/
trait DatasetExtension
{
protected $_externalFields = array(
'TitleMain' => array(
'model' => 'App\Title',
'options' => array('type' => 'main'),
'fetch' => 'eager'
),
'TitleAbstract' => array(
'model' => 'App\Title',
'options' => array('type' => 'abstract'),
'fetch' => 'eager'
),
'Licence' => array(
'model' => 'App\License',
'through' => 'link_documents_licences',
'relation' => 'licenses',
'fetch' => 'eager'
),
'PersonAuthor' => array(
'model' => 'App\Person',
'through' => 'link_documents_persons',
'pivot' => array('role' => 'author'),
//'sort_order' => array('sort_order' => 'ASC'), // <-- We need a sorted authors list.
//'sort_field' => 'SortOrder',
'relation' => 'authors',
'fetch' => 'eager'
),
'PersonContributor' => array(
'model' => 'App\Person',
'through' => 'link_documents_persons',
'pivot' => array('role' => 'contributor'),
// 'sort_order' => array('sort_order' => 'ASC'), // <-- We need a sorted authors list.
//'sort_field' => 'SortOrder',
'relation' => 'contributors',
'fetch' => 'eager'
),
'File' => array(
'model' => 'App\File',
'relation' => 'files',
'fetch' => 'eager'
),
);
protected $_internalFields = array();
protected $_fields = array();
protected function _initFields()
{
$fields = array(
"Id",
"CompletedDate", "CompletedYear",
"ContributingCorporation",
"CreatingCorporation",
"ThesisDateAccepted", "ThesisYearAccepted",
"Edition",
"Issue",
"Language",
"PageFirst", "PageLast", "PageNumber",
"PublishedDate", "PublishedYear",
"PublisherName", "PublisherPlace",
"PublicationState",
"ServerDateCreated",
"ServerDateModified",
"ServerDatePublished",
"ServerDateDeleted",
"ServerState",
"Type",
"Volume",
"BelongsToBibliography",
"EmbargoDate"
);
foreach ($fields as $fieldname) {
$field = new Field($fieldname);
$this->addField($field);
}
foreach (array_keys($this->_externalFields) as $fieldname) {
$field = new Field($fieldname);
$field->setMultiplicity('*');
$this->addField($field);
}
// Initialize available date fields and set up date validator
// if the particular field is present
$dateFields = array(
'ServerDateCreated', 'CompletedDate', 'PublishedDate',
'ServerDateModified', 'ServerDatePublished', 'ServerDateDeleted', 'EmbargoDate'
);
foreach ($dateFields as $fieldName) {
$this->getField($fieldName)
->setValueModelClass('Carbon');
}
// $this->_fetchValues();
}
/**
* Get a list of all fields attached to the model. Filters all fieldnames
* that are defined to be inetrnal in $_internalFields.
*
* @see Opus_Model_Abstract::_internalFields
* @return array List of fields
*/
public function describe()
{
return array_diff(array_keys($this->_fields), $this->_internalFields);
}
public function addField(Field $field)
{
$fieldname = $field->getName();
if (isset($fieldname, $this->_externalFields[$fieldname])) {
$options = $this->_externalFields[$fieldname];
// set ValueModelClass if a through option is given
if (isset($options['model'])) {
$field->setValueModelClass($options['model']);
}
// set LinkModelClass if a through option is given
//if (isset($options['through']))
//{
// $field->setLinkModelClass($options['through']);
//}
}
$this->_fields[$field->getName()] = $field;
$field->setOwningModelClass(get_class($this));
return $this;
}
public function getField($name)
{
return $this->_getField($name);
}
/**
* Return a reference to an actual field.
*
* @param string $name Name of the requested field.
* @return Field The requested field instance. If no such instance can be found, null is returned.
*/
protected function _getField($name)
{
if (isset($this->_fields[$name])) {
return $this->_fields[$name];
} else {
return null;
}
}
public function fetchValues()
{
$this->_initFields();
foreach ($this->_fields as $fieldname => $field) {
if (isset($this->_externalFields[$fieldname]) === true) {
$fetchmode = 'lazy';
if (isset($this->_externalFields[$fieldname]['fetch']) === true) {
$fetchmode = $this->_externalFields[$fieldname]['fetch'];
}
if ($fetchmode === 'lazy') {
// Remember the field to be fetched later.
$this->_pending[] = $fieldname;
// Go to next field
continue;
} else {
// Immediately load external field if fetching mode is set to 'eager'
$this->_loadExternal($fieldname);
}
} else {
// Field is not external an gets handled by simply reading
$property_name = self::convertFieldnameToColumn($fieldname);
//$test = $this->server_date_created;
$fieldval = $this->{$property_name};
// explicitly set null if the field represents a model except for dates
if (null !== $field->getValueModelClass()) {
if (true === empty($fieldval)) {
$fieldval = null;
} else {
$fieldval = new \Carbon\Carbon($fieldval);
}
}
$field->setValue($fieldval);
}
}
}
public static function convertFieldnameToColumn($fieldname)
{
return strtolower(preg_replace('/(?!^)[[:upper:]]/', '_\0', $fieldname));
}
protected function _loadExternal($fieldname)
{
$field = $this->_fields[$fieldname];
$modelclass = $field->getLinkModelClass();
if (!isset($modelclass)) {
// For handling a value model, see 'model' option.
$modelclass = $field->getValueModelClass();
}
$tableclass = new $modelclass();//::getTableGatewayClass();
// $table = Opus_Db_TableGateway::getInstance($tableclass);
$select = $tableclass->query();//->where("document_id", $this->id);;
// If any declared constraints, add them to query
if (isset($this->_externalFields[$fieldname]['options'])) {
$options = $this->_externalFields[$fieldname]['options'];
foreach ($options as $column => $value) {
$select = $select->where($column, $value);
}
}
// Get dependent rows
$result = array();
$datasetId = $this->id;
$rows = array();
if (isset($this->_externalFields[$fieldname]['through'])) {
$relation = $this->_externalFields[$fieldname]['relation'];
//$rows = $select->datasets
////->orderBy('name')
//->get();
//$licenses = $select->with('datasets')->get();
//$rows = $supplier->datasets;
$rows = $this->{$relation};
//if (isset($this->_externalFields[$fieldname]['pivot']))
//{
// $pivArray = $this->_externalFields[$fieldname]['pivot'];
// $rows = $rows->wherePivot('role', $pivArray['role']);
//}
} else {
$rows = $select->whereHas('dataset', function ($q) use ($datasetId) {
$q->where('id', $datasetId);
})->get();
}
foreach ($rows as $row) {
// //$newModel = new $modelclass($row);
// $result[] = $row;//->value;
$attributes = array_keys($row->getAttributes());
$objArray = [];
foreach ($attributes as $property_name) {
$fieldName = self::convertColumnToFieldname($property_name);
// $field =new Field($fieldName);
$fieldval = $row->{$property_name};
// $field->setValue($fieldval);
// $this->_mapField($field, $dom, $rootNode);
$objArray[$fieldName] = $fieldval;
}
$result[] = $objArray;
}
// Set the field value
$field->setValue($result);
}
//snakeToCamel
public static function convertColumnToFieldname($columnname)
{
//return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $columnname))));
return str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $columnname)));
}
}

213
app/Library/Xml/Field.php Normal file
View file

@ -0,0 +1,213 @@
<?php
namespace App\Library\Xml;
/**
* Field short summary.
*
* Field description.
*
* @version 1.0
* @author kaiarn
*/
class Field
{
/**
* Hold multiplicity constraint.
*
* @var Integer|String
*/
protected $_multiplicity = 1;
/**
* Simple check for multiple values.
*
* @var bool
*/
private $_hasMultipleValues = false;
/**
* Holds the classname for external fields.
*
* @var string
*/
protected $_valueModelClass = null;
/**
* Holds the classname for link fields.
*
* @var string
*/
protected $_linkModelClass = null;
/**
* Holds the classname of the model that the field belongs to.
*/
protected $_owningModelClass = null;
/**
* Hold the fields value.
*
* @var mixed
*/
protected $_value = null;
/**
* Create an new field instance and set the given name.
*
* @param string $name Internal name of the field.
*/
public function __construct($name)
{
$this->_name = $name;
}
/**
* Return the name of model class if the field holds model instances.
*
* @return string Class name or null if the value is not a model.
*/
public function getValueModelClass()
{
return $this->_valueModelClass;
}
/**
* Set the name of model class if the field holds model instances.
*
* @param string $classname The name of the class that is used as model for this field or null.
* @return Field Fluent interface.
*/
public function setValueModelClass($classname)
{
$this->_valueModelClass = $classname;
return $this;
}
public function getName()
{
return $this->_name;
}
/**
* Set the name of the model class that owns the field.
* @param string $classname The name of the class that owns the field.
* @return Field Fluent interface.
*/
public function setOwningModelClass($classname)
{
$this->_owningModelClass = $classname;
return $this;
}
public function setValue($value)
{
// If the fields value is not going to change, leave.
if (is_object($value) === true) {
// weak comparison for objects
// TODO: DateTimeZone == DateTimeZone always returns true in weak equal check! Why?
if ($value == $this->_value) {
return $this;
}
} else {
// strong comparison for other values
if ($value === $this->_value) {
return $this;
}
}
// if (true === is_array($value) and 1 === count($value)) {
// //$value = array_pop($value);
// }
if (true === is_array($value) and 0 === count($value)) {
$value = null;
} elseif (is_bool($value)) {
// make sure 'false' is not converted to '' (empty string), but 0 for database
$value = (int)$value;
}
// if null is given, delete dependent objects
if (null === $value) {
//$this->_deleteDependentModels();
} else {
$multiValueCondition = $this->hasMultipleValues();
$arrayCondition = is_array($value);
// arrayfy value
$values = $value;
if (false === $arrayCondition) {
$values = array($value);
}
// remove wrapper array if multivalue condition is not given
if (false === $multiValueCondition) {
$value = $values[0];
}
$this->_value = $value;
return $this;
}
}
public function getValue($index = null)
{
// wrap start value in array if multivalue option is set for this field
$this->_value = $this->_wrapValueInArrayIfRequired($this->_value);
// Caller requested a specific array index
//if (!is_null($index)) {
// if (true === is_array($this->_value)) {
// if (true === isset($this->_value[$index])) {
// return $this->_value[$index];
// }
// else {
// throw new \Exception('Unvalid index: ' . $index);
// }
// }
// else {
// throw new \Exception('Invalid index (' . $index . '). Requested value is not an array.');
// }
//}
return $this->_value;
}
private function _wrapValueInArrayIfRequired($value)
{
if (is_array($value) or !$this->hasMultipleValues()) {
return $value;
}
if (is_null($value)) {
return array();
}
return array($value);
}
public function hasMultipleValues()
{
return $this->_hasMultipleValues;
}
public function setMultiplicity($max)
{
if ($max !== '*') {
if ((is_int($max) === false) or ($max < 1)) {
throw new \Exception('Only integer values > 1 or "*" allowed.');
}
}
$this->_multiplicity = $max;
$this->_hasMultipleValues = (($max > 1) or ($max === '*'));
return $this;
}
/**
* Return the name of model class if the field holds link model instances.
*
* @return string Class name or null if the value is not a model.
*/
public function getLinkModelClass()
{
return $this->_linkModelClass;
}
}

View file

@ -0,0 +1,232 @@
<?php
namespace App\Library\Xml;
use App\Dataset;
use DOMDocument;
/**
* Strategy short summary.
*
* Strategy description.
*
* @version 1.0
* @author kaiarn
*/
class Strategy
{
/**
* Holds current configuration.
*
* @var Conf
*/
private $_config;
/**
* Holds current representation version.
*
* @var double
*/
protected $_version = null;
/**
* Initiate class with a valid config object.
*/
public function __construct()
{
$this->_version = 1.0;
$this->_config = new Conf();
}
/**
* (non-PHPdoc)
* see library/Opus/Model/Xml/Opus_Model_Xml_Strategy#setDomDocument()
*/
public function setup(Conf $conf)
{
$this->_config = $conf;
}
/**
* If a model has been set this method generates and returnes
* DOM representation of it.
*
* @throws \Exception Thrown if no Model is given.
* @return \DOMDocument DOM representation of the current Model.
*/
public function getDomDocument()
{
if (null === $this->_config->model) {
throw new \Exception('No Model given for serialization.');
}
$this->_config->dom = new DOMDocument('1.0', 'UTF-8');
$root = $this->_config->dom->createElement('Opus');
$root->setAttribute('version', $this->getVersion());
$this->_config->dom->appendChild($root);
$root->setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
$this->_mapModel($this->_config->model, $this->_config->dom, $root);
return $this->_config->dom;
}
protected function _mapModel(Dataset $model, \DOMDocument $dom, \DOMNode $rootNode)
{
$fields = $model->describe();
$excludeFields = $this->getConfig()->excludeFields;
if (count($excludeFields) > 0) {
$fieldsDiff = array_diff($fields, $excludeFields);
} else {
$fieldsDiff = $fields;
}
$childNode = $this->createModelNode($dom, $model);
$rootNode->appendChild($childNode);
foreach ($fieldsDiff as $fieldname) {
$field = $model->getField($fieldname);
$this->_mapField($field, $dom, $childNode);
}
}
protected function _mapField(Field $field, DOMDocument $dom, \DOMNode $rootNode)
{
$modelClass = $field->getValueModelClass();
$fieldValues = $field->getValue();
if (true === $this->getConfig()->excludeEmpty) {
if (true === is_null($fieldValues)
or (is_string($fieldValues) && trim($fieldValues) == '')
or (is_array($fieldValues) && empty($fieldValues))) {
return;
}
}
if (null === $modelClass) {
$this->mapSimpleField($dom, $rootNode, $field);
} else {
$fieldName = $field->getName();
if (!is_array($fieldValues)) {
$fieldValues = array($fieldValues);
}
foreach ($fieldValues as $value) {
$childNode = $this->createFieldElement($dom, $fieldName);
//$childNode->setAttribute("Value", $value);
$rootNode->appendChild($childNode);
// if a field has no value then is nothing more to do
// TODO maybe must be there an other solution
// FIXME remove code duplication (duplicates Opus_Model_Xml_Version*)
if (is_null($value)) {
continue;
}
if ($value instanceof \Illuminate\Database\Eloquent\Model) {
$this->_mapModelAttributes($value, $dom, $childNode);
} elseif ($value instanceof \Carbon\Carbon) {
$this->_mapDateAttributes($value, $dom, $childNode);
} elseif (is_array($value)) {
$this->_mapArrayAttributes($value, $dom, $childNode);
}
}
}
}
public function mapSimpleField(DOMDocument $dom, \DOMNode $rootNode, Field $field)
{
$fieldName = $field->getName();
$fieldValues = $this->getFieldValues($field);
// Replace invalid XML-1.0-Characters by UTF-8 replacement character.
$fieldValues = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', "\xEF\xBF\xBD ", $fieldValues);
$rootNode->setAttribute($fieldName, $fieldValues);
}
protected function createFieldElement(DOMDocument $dom, $fieldName)
{
return $dom->createElement($fieldName);
}
protected function _mapDateAttributes(\Carbon\Carbon $model, DOMDocument $dom, \DOMNode $rootNode)
{
$rootNode->setAttribute("Year", $model->year);
$rootNode->setAttribute("Month", $model->month);
$rootNode->setAttribute("Day", $model->day);
$rootNode->setAttribute("Hour", $model->hour);
$rootNode->setAttribute("Minute", $model->minute);
$rootNode->setAttribute("Second", $model->second);
$rootNode->setAttribute("UnixTimestamp", $model->timestamp);
$rootNode->setAttribute("Timezone", $model->tzName);
}
protected function _mapArrayAttributes(array $attributes, DOMDocument $dom, \DOMNode $rootNode)
{
//$attributes = array_keys($model->getAttributes());
foreach ($attributes as $property_name => $value) {
$fieldName = $property_name;
$field = new Field($fieldName);
$fieldval = $value;
$field->setValue($fieldval);
$this->_mapField($field, $dom, $rootNode);
}
}
protected function _mapModelAttributes(\Illuminate\Database\Eloquent\Model $model, DOMDocument $dom, \DOMNode $rootNode)
{
$attributes = array_keys($model->getAttributes());
foreach ($attributes as $property_name) {
$fieldName = self::convertColumnToFieldname($property_name);
$field = new Field($fieldName);
$fieldval = $model->{$property_name};
$field->setValue($fieldval);
$this->_mapField($field, $dom, $rootNode);
}
}
//snakeToCamel
public static function convertColumnToFieldname($columnname)
{
//return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $columnname))));
return str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $columnname)));
}
public function getFieldValues($field)
{
$fieldValues = $field->getValue();
// workaround for simple fields with multiple values
if (true === $field->hasMultipleValues()) {
$fieldValues = implode(',', $fieldValues);
}
//if ($fieldValues instanceOf DateTimeZone) {
// $fieldValues = $fieldValues->getName();
//}
return trim($fieldValues);
}
protected function createModelNode(DOMDocument $dom, Dataset $model)
{
$classname = "Rdr_" . substr(strrchr(get_class($model), '\\'), 1);
return $dom->createElement($classname);
}
/**
* Return version value of current xml representation.
*
* @see library/Opus/Model/Xml/Opus_Model_Xml_Strategy#getVersion()
*/
public function getVersion()
{
return floor($this->_version);
}
public function getConfig()
{
return $this->_config;
}
}

View file

@ -0,0 +1,180 @@
<?php
/**
* Footer
*
* Main footer file for the theme.
*
* @category Components
* @package ResearchRepository
* @subpackage Publish
* @author Your Name <yourname@example.com>
* @license https://www.gnu.org/licenses/gpl-3.0.txt GNU/GPLv3
* @link https://gisgba.geologie.ac.at
* @since 1.0.0
*/
namespace App\Library\Xml;
use App\XmlCache;
use Illuminate\Support\Facades\Log;
class XmlModel
{
/**
* Holds current configuration.
* @var Conf
*/
private $_config = null;
/**
* Holds current xml strategy object.
* @var Strategy
*/
private $_strategy = null;
/**
* TODO
* @var XmlCache
*/
private $_cache = null;
/**
* Do some initial stuff like setting of a XML version and an empty
* configuration.
*/
public function __construct()
{
$this->_strategy = new Strategy();// Opus_Model_Xml_Version1;
$this->_config = new Conf();
$this->_strategy->setup($this->_config);
}
/**
* Set a new XML version with current configuration up.
*
* @param Strategy $strategy Version of Xml to process
*
* @return XmlModel fluent interface.
*/
public function setStrategy(Strategy $strategy)
{
$this->_strategy = $strategy;
$this->_strategy->setup($this->_config);
return $this;
}
/**
* Set a new XML version with current configuration up.
*
* @param XmlCache $cache cach table
*
* @return XmlModel fluent interface.
*/
public function setXmlCache(XmlCache $cache)
{
$this->_cache = $cache;
return $this;
}
/**
* Return cache table.
*
* @return XmlCache
*/
public function getXmlCache()
{
return $this->_cache;
}
/**
* Set the Model for XML generation.
*
* @param \App\Dataset $model Model to serialize.
*
* @return XmlModel Fluent interface.
*/
public function setModel($model)
{
$this->_config->model = $model;
return $this;
}
/**
* Define that empty fields (value===null) shall be excluded.
*
* @return XmlModel Fluent interface
*/
public function excludeEmptyFields()
{
$this->_config->excludeEmpty = true;
return $this;
}
/**
* If a model has been set this method generates and returnes
* DOM representation of it.
*
* @return \DOMDocument DOM representation of the current Model.
*/
public function getDomDocument()
{
$dataset = $this->_config->model;
$domDocument = $this->getDomDocumentFromXmlCache();
if (!is_null($domDocument)) {
return $domDocument;
}
//create xml:
$domDocument = $this->_strategy->getDomDocument();
//if caching is not desired, return domDocument
if (is_null($this->_cache)) {
return $domDocument;
} else {
//create cache relation
$this->_cache->fill(array(
'document_id' => $dataset->id,
'xml_version' => (int)$this->_strategy->getVersion(),
'server_date_modified' => $dataset->server_date_modified,
'xml_data' => $domDocument->saveXML()
));
$this->_cache->save();
Log::debug(__METHOD__ . ' cache refreshed for ' . get_class($dataset) . '#' . $dataset->id);
return $domDocument;
}
}
/**
* This method tries to load the current model from the xml cache. Returns
* null in case of an error/cache miss/cache disabled. Returns DOMDocument
* otherwise.
*
* @return \DOMDocument DOM representation of the current Model.
*/
private function getDomDocumentFromXmlCache()
{
$dataset = $this->_config->model;
if (null === $this->_cache) {
//$logger->debug(__METHOD__ . ' skipping cache for ' . get_class($model));
Log::debug(__METHOD__ . ' skipping cache for ' . get_class($dataset));
return null;
}
//$cached = $this->_cache->hasValidEntry(
// $dataset->id,
// (int) $this->_strategy->getVersion(),
// $dataset->server_date_modified
//);
//$cached = false;
$cache = XmlCache::where('document_id', $dataset->id)
->first();// model or null
if (!$cache) {
Log::debug(__METHOD__ . ' cache miss for ' . get_class($dataset) . '#' . $dataset->id);
return null;
} else {
return $cache->getDomDocument();
}
}
}