drupal_admin_app-2.1.x-dev/src/Plugin/rest/resource/RestAdminops.php
src/Plugin/rest/resource/RestAdminops.php
<?php
namespace Drupal\drupal_admin_app\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\node\Entity\NodeType;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
/**
* Provides a resource for database watchdog log entries.
*
* @RestResource(
* id = "dn_adminopa",
* label = @Translation("Drupal Admin App"),
* uri_paths = {
* "canonical" = "/dnadmin/{id}",
* "create" = "/rest/dnadmin/data"
* }
* )
*/
class RestAdminops extends ResourceBase {
/**
* Responds to GET requests.
*
* Returns a watchdog log entry for the specified ID.
*
* @param int $id
* The ID of the watchdog log entry.
*
* @return \Drupal\rest\ResourceResponse
* The response containing the log entry.
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
* Thrown when the log entry was not found.
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* Thrown when no log entry was provided.
*/
public function get($id = NULL) {
if ($id) {
$record = db_query("SELECT * FROM {watchdog} WHERE wid = :wid", [':wid' => $id])
->fetchAssoc();
if (!empty($record)) {
return new ResourceResponse($record);
}
throw new NotFoundHttpException('Log entry with ID @id was not found', ['@id' => $id]);
}
throw new BadRequestHttpException('No log entry ID was provided');
}
/**
* Responds to POST requests.
*
* @return \Drupal\rest\ResourceResponse
* The HTTP response object.
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
* Throws exception expected.
*/
public function post($data) {
$result_arr = ['message' => '', 'status' => 'false', 'ops' => $data["ops"], 'roles' => '','content_types'=>''];
$dash_arr = ['message' => '', 'status' => 'false','total_contents' => '', 'total_users'=> ''];
// =====
// $result_arr['roles'] = [] ;
// $roles = \Drupal::currentUser()->getRoles();
if($data["ops"] == "roles"){
$roles = \Drupal::entityTypeManager()->getStorage('user_role')->loadMultiple();
$result_arr['roles'] = $roles;
// =====
$response = new ResourceResponse($result_arr);
$response->addCacheableDependency($result_arr);
return $response;
} else if($data["ops"] == "contenttypes"){
$types = NodeType::loadMultiple();
$result = [];
foreach ($types as $type) {
$types_arr[] = [
'machine_name' => $type->id(),
'label' => $type->label(),
];
$result_arr['content_types'] = $types_arr;
}
$response = new ResourceResponse($result_arr);
$response->addCacheableDependency($result_arr);
return $response;
} else if( $data["ops"] == "dashboard" ){
$query_node = \Drupal::entityQuery('node');
$total_contents = $query_node->accessCheck(TRUE)->count()->execute();
// Get total user count (excluding anonymous user [uid 0])
$total_users = \Drupal::entityQuery('user')
->accessCheck(TRUE)
->condition('uid', 0, '>') // exclude anonymous
->count()
->execute();
//=====top 3 recent users
$date_formatter = \Drupal::service('date.formatter');
$query_users = \Drupal::entityQuery('user')
->accessCheck(TRUE)
->condition('uid', 0, '>') // Exclude anonymous user
->sort('created', 'DESC') // Newest first
->range(0, 3); // Top 3 users
$uids = $query_users->execute();
$users = User::loadMultiple($uids);
$users_arr = [];
foreach ($users as $user) {
$roles = $user->getRoles();
// Remove the 'authenticated' role which all users have by default
$roles = array_diff($roles, ['authenticated']);
// Convert roles array to comma-separated string
$roles_string = implode(',', $roles);
$created = $date_formatter->format($user->getCreatedTime(), 'custom', 'Y-m-d H:i:s');
$access_time = $user->getLastAccessedTime();
$access_formatted = $access_time > 0
? $date_formatter->format($access_time, 'custom', 'Y-m-d H:i:s')
: 'never';
$status = '';
if ($user->isActive()){
$status = 'Active';
}else{
$status = 'Inactive';
}
$users_arr[] = [
'name' => $user->getAccountName(),
'status' => $status,
'roles_target_id' => $roles_string,
'created' => $created,
'access' => $access_formatted,
'uid' => $user->id(),
'uuid' => $user->uuid(),
'user_picture' => $user->get('user_picture')->isEmpty()
? ''
: file_create_url($user->get('user_picture')->entity->getFileUri()),
'mail_1' => $user->getEmail(),
'nothing' => "$total_users"
];
}
//=====top 3 recent users
//======recent 3 contents
// Step 1: Query for the most recent 3 published nodes
$nids = \Drupal::entityQuery('node')
->accessCheck(TRUE)
->condition('status', 1) // Published only
->sort('created', 'DESC') // Most recent first
->range(0, 3) // Limit to top 3
->execute();
// Step 2: Load the node entities
$nodes = Node::loadMultiple($nids);
// Step 3: Process or return node data
$top_nodes = [];
foreach ($nodes as $node) {
$author = $node->getOwner();
$created_date = \Drupal::service('date.formatter')->format($node->getCreatedTime(), 'custom', 'Y-m-d');
$updated_date = \Drupal::service('date.formatter')->format($node->getChangedTime(), 'custom', 'Y-m-d');
$top_nodes[] = [
'title' => $node->getTitle(),
'contentType' => $node->bundle(),
'authorName' => $author ? $author->getDisplayName() : 'Anonymous',
'status' => ($node->isPublished())?'Published':'Unpublished',
'updatedDate' => $updated_date,
'createdDate' => $created_date,
'nid' => $node->id(),
'body' => $node->hasField('body') && !$node->get('body')->isEmpty() ? $node->get('body')->value : '', // Raw body content
// Alternative for formatted body:
// 'bodyFormatted' => $node->hasField('body') && !$node->get('body')->isEmpty()
// ? $node->get('body')->processed
// : '',
'nothing' => "$total_users"
];
}
//======recent 3 content
$dash_arr['total_contents'] = $total_contents;
$dash_arr['total_users'] = $total_users;
$dash_arr['recent_users'] = $users_arr;
$dash_arr['recent_contents'] = $top_nodes;
$response = new ResourceResponse($dash_arr);
$response->addCacheableDependency($dash_arr);
return $response;
}
}
}
