marketo_ma-8.x-2.x-dev/src/FieldDefinitionSet.php
src/FieldDefinitionSet.php
<?php
namespace Drupal\marketo_ma;
use Drupal\Core\Database\Database;
/**
* A service for interacting with the set of fields in Marketo.
*/
class FieldDefinitionSet {
/**
* A list of all fields.
*
* @var \Drupal\marketo_ma\MarketoFieldDefinition[]
*/
private $fieldset = [];
/**
* A list of readable fields.
*
* @var \Drupal\marketo_ma\MarketoFieldDefinition[]
*/
private $readonly = [];
/**
* A list of writeable fields.
*
* @var \Drupal\marketo_ma\MarketoFieldDefinition[]
*/
private $writeable = [];
/**
* Construct a field definition set.
*/
public function __construct() {
$this->load();
}
/**
* Load all field maps from the database.
*/
private function load() {
$data = Database::getConnection()->select('marketo_ma_lead_fields', 'f')
->fields('f')
// We don't have an index on this. What's the reason for it?
->orderBy('displayName')
->execute()
->fetchAllAssoc('restName', \PDO::FETCH_ASSOC);
$this->fieldset = array_map(
function (array $field) {
return new MarketoFieldDefinition($field);
},
$data
);
foreach ($this->fieldset as $field_key => $field_value) {
if ($field_value->getRestReadOnly() || $field_value->getSoapReadOnly()) {
$this->readonly[$field_key] = $field_value;
}
else {
$this->writeable[$field_key] = $field_value;
}
}
}
/**
* Reload the current fieldset from the database.
*/
public function reload() {
$this->load();
}
/**
* Store a field map to the database.
*
* @param array $field
* Raw field definition from Marketo.
*/
public function add(array $field) {
Database::getConnection()->merge('marketo_ma_lead_fields')
->key('restName', $field['rest']['name'])
->fields([
'displayName' => $field['displayName'],
'dataType' => $field['dataType'],
'length' => $field['length'] ?? NULL,
'restName' => $field['rest']['name'] ?? NULL,
'restReadOnly' => (isset($field['rest']['readOnly']) && $field['rest']['readOnly']) ? 1 : 0,
'soapName' => $field['soap']['name'] ?? NULL,
'soapReadOnly' => (isset($field['soap']['readOnly']) && $field['soap']['readOnly']) ? 1 : 0,
])
->execute();
}
/**
* Get a list of all fieldmaps.
*
* @return \Drupal\marketo_ma\MarketoFieldDefinition[]
* A list of all fields.
*/
public function getAll() {
return $this->fieldset;
}
/**
* Get a list of all read only fields.
*
* @return \Drupal\marketo_ma\MarketoFieldDefinition[]
* A list of fields that are read only in some methods.
*/
public function getReadOnly() {
return $this->readonly;
}
/**
* Get a list of all writeable fields.
*
* Note: Writeable might not mean writeable with your method. Check soap/rest.
*
* @return \Drupal\marketo_ma\MarketoFieldDefinition[]
* A list of fields that are always writeable.
*/
public function getWriteable() {
return $this->writeable;
}
}
