View source
<?php
namespace Drupal\pcp;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\field\FieldConfigInterface;
use Drupal\user\UserInterface;
class PcpService implements PcpServiceInterface {
protected $entityFieldManager;
protected $config;
public function __construct(EntityFieldManagerInterface $entityFieldManager, ConfigFactoryInterface $configFactory) {
$this->entityFieldManager = $entityFieldManager;
$this->config = $configFactory
->get('pcp.settings');
}
public function getCompletePercentageData(UserInterface $user) {
$userFields = $this
->getUserFields();
$profileFields = array_filter($this->config
->get('profile_fields'));
$profileFields = array_intersect_key($profileFields, $userFields);
if (empty($profileFields)) {
return [
'current_percent' => 100,
'next_percent' => 0,
];
}
$emptyFields = [];
foreach ($profileFields as $fieldName) {
if ($user
->get($fieldName)
->isEmpty()) {
$emptyFields[$fieldName] = $userFields[$fieldName]
->label();
}
}
$fieldCount = count($profileFields);
$emptyFieldCount = count($emptyFields);
$completedFieldCount = $fieldCount - $emptyFieldCount;
$nextField = $this
->getNextField($emptyFields);
$nextFieldTitle = isset($emptyFields[$nextField]) ? $emptyFields[$nextField] : '';
return [
'uid' => $user
->id(),
'total' => $fieldCount,
'open_link' => $this->config
->get('open_link') == 0 ? '_self' : '_target',
'completed' => $completedFieldCount,
'incomplete' => $emptyFieldCount,
'hide_pcp_block' => (bool) $this->config
->get('hide_block_on_complete'),
'nextfield_title' => $nextFieldTitle,
'current_percent' => $this
->calcCurrentPercentage($completedFieldCount, $fieldCount),
'next_percent' => $this
->calcNextPercentage($completedFieldCount, $fieldCount),
'nextfield_name' => str_replace('_', '-', $nextField),
];
}
protected function getUserFields() {
$fields = array_filter($this->entityFieldManager
->getFieldDefinitions('user', 'user'), function ($field_definition) {
return $field_definition instanceof FieldConfigInterface;
});
return $fields;
}
protected function getNextField(array $fields) {
if (empty($fields)) {
return '';
}
if ($this->config
->get('field_order') == 0) {
return array_rand($fields);
}
return key($fields);
}
protected function calcCurrentPercentage($completed, $total) {
if ($total === 0) {
return 0;
}
return round($completed * 100 / $total);
}
protected function calcNextPercentage($completed, $total) {
if ($total === 0) {
return 0;
}
return round(($completed + 1) * 100 / $total);
}
}