Commit 1e7919e3 authored by Abhi Rijal's avatar Abhi Rijal
Browse files

updated controllers and caching

parent 733c344f
......@@ -27,76 +27,74 @@ use App\Service\LockupsGenerator;
use App\Service\Core;
use App\Service\Engine;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
class CreateLockupsController extends BaseController
{
/**
* @Route("/lockups/create2/", name="createLockups2", methods={"GET"})
* @Route("/lockups/create/", name="createLockups2", methods={"GET"})
*/
public function createLockups2(ManagerRegistry $doctrine, Auth $auth): Response
public function createLockups(ManagerRegistry $doctrine, Auth $auth, Lockups $lockups = null, array $lockupFields = array(), array $errorMsg = null): Response
{
$auth->requireAuth();
$lockups_fields = $doctrine->getRepository(LockupTemplatesFields::class)->findAll();
$all_lockups_fields = $doctrine->getRepository(LockupTemplatesFields::class)->findAll();
$lockups_categories = $doctrine->getRepository(LockupTemplatesCategories::class)->findAll();
// convert lockup fields to JSON
$tempJson = array();
foreach ($lockups_fields as $lockupFields) {
$tempArr = array();
$tempArr['slug'] = $lockupFields->getSlug();
$tempArr['uppercase'] = $lockupFields->getUppercase();
$tempArr['value'] = $lockupFields->getValue();
array_push($tempJson, $tempArr);
$approverList = $doctrine->getRepository(Users::class)->findBy(['role' => 'approver'], ['name' => 'ASC']);
// convert doctrine objects to JSON
$encoders = [new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
$json_lockups_fields = $serializer->serialize($all_lockups_fields, 'json', [AbstractNormalizer::ATTRIBUTES => ['slug', 'uppercase', 'value']]);
if ($lockups != null && count($lockupFields) == 0) {
$lockupFields = null;
} elseif ($lockups != null && count($lockupFields) > 0) {
$lockupFields = $serializer->serialize($lockupFields, 'json', [AbstractNormalizer::ATTRIBUTES => ['fields' => ["slug"], 'value']]);
}
$approverList = $doctrine->getRepository(Users::class)->findBy(['role' => 'approver'],['name' => 'ASC']);
// $lockupsFields = null ;
// echo (var_dump($lockups));
return $this->render('base.html.twig', [
'page_template' => "createLockups2.html.twig",
'page_template' => "createLockups.html.twig",
'page_name' => "CreateLockups",
'lockup_categories' => $lockups_categories,
'lockups_fields' => $lockups_fields,
'lockups_fields_json' => json_encode($tempJson),
'all_lockups_fields' => $all_lockups_fields,
'all_lockups_fields_json' => $json_lockups_fields,
'user' => $auth,
'approvers' => $approverList
'approvers' => $approverList,
'lockups' => $lockups,
'lockupFields' => $lockupFields,
'error_msg' => $errorMsg
]);
}
/**
* @Route("/lockups/create2/", name="addLockup2", methods={"POST"})
* @Route("/lockups/create/", name="addLockup2", methods={"POST"})
*/
public function addLockup2(Request $request, ManagerRegistry $doctrine, ValidatorInterface $validator, Auth $auth, LockupsGenerator $lockupsGenerator, int $id = 0)
public function addLockup(Request $request, ManagerRegistry $doctrine, ValidatorInterface $validator, Auth $auth, LockupsGenerator $lockupsGenerator, int $id = 0)
{
$auth->requireAuth();
$errorMsg = array(
"title" => "",
"body" => ""
);
$fields = $doctrine->getRepository(LockupTemplatesFields::class)->findAll();
$errorMsg = array();
$entityManager = $doctrine->getManager();
$lockuptemplate = (int)$request->request->get('lockuptemplate');
$lockupTemplateID = (int)$request->request->get('lockuptemplate');
$approver = (int)$request->request->get('approver');
$approverUser = $doctrine->getRepository(Users::class)->find($approver);
$institution = (string)$request->get('institution');
$department = (string)$request->get('department');
$lockupName = (string)$request->get('lockupName');
$lockups = ($id != 0) ? $doctrine->getRepository(Lockups::class)->find($id) : new Lockups;
$template = $doctrine->getRepository(LockupTemplates::class)->find($lockuptemplate);
$arr = [];
$count = 0;
$lockupTemplates = $doctrine->getRepository(LockupTemplates::class)->find($lockupTemplateID);
// for setting correct user if admin edits lockup
if ($id != 0) {
$originalUser = $lockups->getUser();
} else {
$originalUser = $auth->getUser();
}
// lockup not found
if ($id != 0) {
$lockups = $doctrine->getRepository(Lockups::class)->find($id);
// lockup not found
if ($lockups == null) {
$response = $this->forward('App\Controller\LockupsController::errorPage', [
'errorTitle' => "Not found!",
......@@ -104,14 +102,30 @@ class CreateLockupsController extends BaseController
]);
return $response;
}
// delete existing fields
foreach ($lockups->getLockupsFields() as $existingLockupFields) {
$lockups->removeLockupsFields($existingLockupFields);
}
//delete existing files
foreach ($lockups->getLockupFiles() as $existingLockupFields) {
$lockups->removeLockupFile($existingLockupFields);
}
} else {
$lockups = new Lockups;
$lockups->setUser($auth->getUser());
}
$lockups->setApprover($approverUser);
$lockups->setTemplate($template);
if ($approver != -1 && $approver != 0) {
$approverUser = $doctrine->getRepository(Users::class)->find($approver); // add check for approver if null or not
$lockups->setApprover($approverUser); // add verify approver script
}
$lockups->setTemplate($lockupTemplates);
$lockups->setStatus(0);
$lockups->setDepartment($department);
$lockups->setName($lockupName);
$lockups->setInstitution($institution);
$lockups->setUser($originalUser);
$lockups->setCommunicatorStatus(0);
$lockups->setCreativeStatus(0);
$lockups->setIsGenerated(0);
......@@ -119,74 +133,66 @@ class CreateLockupsController extends BaseController
$lockups->setPublic(1);
$lockups->setDateCreated(new \DateTime());
$errors = $validator->validate($lockups);
$lockupsStyle = array(
'lockup_id' => $lockups->getId(),
'style' => $template->getStyle(),
'category' => $template->getCategory()->getSlug(),
'template_id' => $template->getId(),
'institution' => $institution,
'department' => $department,
'approver' => $approver
);
foreach ($fields as $item) {
if (($request->request->get($item->getSlug())) != "" && (($request->request->get($item->getSlug())) != "0")) {
$arr[$count] = new LockupsFields;
$arr[$count]->setLockup($lockups);
$arr[$count]->setFields($item);
$arr[$count]->setValue($request->request->get($item->getSlug()));
// $entityManager->persist($arr[$count]); don't persist it now as it might casue an error
$count++;
$entityManager->persist($lockups);
$tempLockupFields = array();
$emptyLockupFields = false;
foreach ($lockupTemplates->getTemplateFields() as $templateFields) {
$lockupTemplateFieldSlug = $templateFields->getLockupFields()->getSlug();
if ($request->request->get($lockupTemplateFieldSlug) != "") {
$temp = new LockupsFields;
$temp->setLockup($lockups);
$temp->setFields($templateFields->getLockupFields());
$temp->setValue($request->request->get($lockupTemplateFieldSlug));
array_push($tempLockupFields, $temp);
$entityManager->persist($temp);
// $lockups->addLockupsFields($temp);
} else {
$emptyLockupFields = true;
}
}
// error checking
if (count($errors) > 0) {
$errorMsg['title'] = "Error";
if ($emptyLockupFields == true) {
$errorMsg['title'] = "Empty Field";
$errorMsg['body'] = "You have an error in your submission.";
$response = $this->forward('App\Controller\LockupsController::createLockups', [
$response = $this->forward('App\Controller\CreateLockupsController::createLockups2', [
'errorMsg' => $errorMsg,
'fields' => $arr,
'lockupStyle' => $lockupsStyle
'lockups' => $lockups,
'lockupFields' => $tempLockupFields
]);
return $response;
}
// error checking
if (count($errors) > 0) {
$errorMsg['title'] = "Error";
$errorMsg['body'] = "You have an error in your submission.";
$response = $this->forward('App\Controller\CreateLockupsController::createLockups2', [
'errorMsg' => $errorMsg,
'lockups' => $lockups,
'lockupFields' => $tempLockupFields
foreach ($fields as $item) {
if (($request->request->get($item->getSlug())) == "") {
$errorMsg['title'] = "Empty Field";
$errorMsg['body'] = "Please enter the " . $item->getName() . " field.";
$response = $this->forward('App\Controller\LockupsController::createLockups', [
'errorMsg' => $errorMsg,
'fields' => $arr,
'lockupStyle' => $lockupsStyle
]);
return $response;
}
]);
return $response;
}
if (($department == "") && ($institution =! "")) {
if ($institution == "") {
$errorMsg['title'] = "Error!";
$errorMsg['body'] = "Please enter your Lockup Name.";
$response = $this->forward('App\Controller\LockupsController::createLockups', [
$errorMsg['body'] = "Please enter your Institution Name/ Acronym.";
$response = $this->forward('App\Controller\CreateLockupsController::createLockups2', [
'errorMsg' => $errorMsg,
'fields' => $arr,
'lockupStyle' => $lockupsStyle
'lockups' => $lockups,
'lockupFields' => $tempLockupFields
]);
return $response;
}
if (($department =! "") && ($institution == "")) {
if ($lockupName == "") {
$errorMsg['title'] = "Error!";
$errorMsg['body'] = "Please enter your Institution/Department name.";
$response = $this->forward('App\Controller\LockupsController::createLockups', [
$errorMsg['body'] = "Please enter your Lockups name.";
$response = $this->forward('App\Controller\CreateLockupsController::createLockups2', [
'errorMsg' => $errorMsg,
'fields' => $arr,
'lockupStyle' => $lockupsStyle
'lockups' => $lockups,
'lockupFields' => $tempLockupFields
]);
return $response;
}
......@@ -196,55 +202,28 @@ class CreateLockupsController extends BaseController
if (($approver == 0)) {
$errorMsg['title'] = "Error!";
$errorMsg['body'] = "Please select your Communicator Contract.";
$response = $this->forward('App\Controller\LockupsController::createLockups', [
$response = $this->forward('App\Controller\CreateLockupsController::createLockups2', [
'errorMsg' => $errorMsg,
'fields' => $arr,
'lockupStyle' => $lockupsStyle
'lockups' => $lockups,
'lockupFields' => $tempLockupFields
]);
return $response;
}
// end of error checking
if ($id != 0) {
// delete existing fields
$delete_lockup_fields = $doctrine->getRepository(LockupsFields::class)->findBy(['lockup' => $id]);
$delete_entityManager = $doctrine->getManager();
foreach ($delete_lockup_fields as $item) {
$delete_entityManager->remove(($item));
}
//delete existing files
$delete_lockup_files = $doctrine->getRepository(LockupFiles::class)->findBy(['lockup' => $id]);
foreach ($delete_lockup_files as $item) {
$delete_entityManager->remove(($item));
}
$delete_entityManager->flush();
$editedLockup = true;
} else {
$editedLockup = false;
}
// now we can finally persist the contents of the array now
foreach ($arr as $eachField) {
$entityManager->persist($eachField);
}
$lockupFields = $doctrine->getRepository(LockupsFields::class)->findBy(['lockup' => $id]);
$entityManager->persist($lockups);
$entityManager->flush();
// add lockup fields now
// foreach($lockupFieldsArray as $eachLockupFields) {
// $lockups->addLockupsFields($eachLockupFields);
// }
// $entityManager->persist($lockups);
// $entityManager->flush();
$lockupsGenerator->createPreview($lockups->getId());
if ($id != 0) {
return $this->redirectToRoute('previewLockups', [
'id' => $id,
'action' => "edit-lockup"
], 302);
}
// return $this->redirectToRoute('manageLockups', [], 302);
return $this->redirectToRoute('previewLockups', [
'id' => $lockups->getId(),
'action' => "new-lockup"
], 302);
'id' => $lockups->getId()
], 302);
}
}
......@@ -12,7 +12,7 @@ use WDN\Bundle\FrameworkBundle\Controller\BaseController;
use App\Service\Auth;
class IndexController extends BaseController
class HomePage extends BaseController
{
/**
* @Route("/", name="homePage", methods={"GET"})
......
This diff is collapsed.
......@@ -35,7 +35,7 @@ class Lockups
private $institution;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private $department;
private $name;
#[ORM\Column(type: 'integer', options:["default"=> 0])]
private $Generating;
......@@ -156,14 +156,14 @@ class Lockups
return $this;
}
public function getDepartment(): ?string
public function getName(): ?string
{
return $this->department;
return $this->name;
}
public function setDepartment(?string $department): self
public function setName(?string $name): self
{
$this->department = $department;
$this->name = $name;
return $this;
}
......
......@@ -8,6 +8,9 @@ use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Query\Parameter;
/**
* @method LockupsFields|null find($id, $lockMode = null, $lockVersion = null)
* @method LockupsFields|null findOneBy(array $criteria, array $orderBy = null)
......@@ -65,16 +68,31 @@ class LockupsFieldsRepository extends ServiceEntityRepository
/**
* @return LockupsFields[] Returns an array of LockupsFields objects
*/
public function searchField(string $value): array
public function searchField(string $value, int $id = null): array
{
$entityManager = $this->getEntityManager();
$query = $entityManager->createQuery(
'SELECT p
FROM App\Entity\LockupsFields p
WHERE p.value LIKE :value
ORDER BY p.value ASC'
)->setParameter('value', '%'.$value.'%');
if ($id != null) {
$query = $entityManager->createQuery(
'SELECT p
FROM App\Entity\LockupsFields p
WHERE p.value LIKE :value
-- AND
-- p.lockups.id = :id
ORDER BY p.value ASC'
)->setParameters(new ArrayCollection([
new Parameter('value', '%' . $value . '%')
// new Parameter('id', $id)
]));
} else {
$query = $entityManager->createQuery(
'SELECT p
FROM App\Entity\LockupsFields p
WHERE p.value LIKE :value
ORDER BY p.value ASC'
)->setParameter('value', '%'.$value.'%');
}
// returns an array of Product objects
return $query->getResult();
......
......@@ -6,6 +6,10 @@ use App\Entity\Lockups;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Query\Parameter;
use Doctrine\Persistence\ManagerRegistry;
/**
......@@ -48,20 +52,36 @@ class LockupsRepository extends ServiceEntityRepository
/**
* @return Lockups[] Returns an array of LockupsFields objects
*/
public function searchNames(string $value): array
public function searchNames(string $value, int $id = null): array
{
$searchArr = [];
$entityManager = $this->getEntityManager();
$institutionQuery = $entityManager->createQuery(
'SELECT p
FROM App\Entity\Lockups p
WHERE p.institution LIKE :value
OR
p.department LIKE :value
ORDER BY p.institution ASC'
)->setParameter('value', '%' . $value . '%');
if ($id != null) {
$institutionQuery = $entityManager->createQuery(
'SELECT p
FROM App\Entity\Lockups p
WHERE p.institution LIKE :value
OR
p.name LIKE :value
AND
p.user = :id
ORDER BY p.name ASC'
)->setParameters(new ArrayCollection([
new Parameter('value', '%' . $value . '%'),
new Parameter('id', $id)
]));
} else {
$institutionQuery = $entityManager->createQuery(
'SELECT p
FROM App\Entity\Lockups p
WHERE p.institution LIKE :value
OR
p.name LIKE :value
ORDER BY p.name ASC'
)->setParameter('value', '%' . $value . '%');
}
// returns an array of Product objects
return $institutionQuery->getResult();
......
......@@ -3,6 +3,7 @@
namespace App\Service;
use App\Entity\Users;
use App\Service\Engine;
use Doctrine\Persistence\ManagerRegistry;
use phpCAS;
......@@ -13,13 +14,17 @@ class Auth
private $directory_url = 'https://directory.unl.edu/';
private $entityManager;
private $root_url;
private $engine;
public function __construct(ManagerRegistry $doctrine, string $appUrl)
public function __construct(ManagerRegistry $doctrine, string $appUrl, Engine $engine)
{
$this->doctrine = $doctrine;
$this->entityManager = $doctrine->getManager();
$this->root_url = $appUrl;
$this->engine = $engine;
// $this->engine = $engine;
if (!phpCAS::isInitialized()) {
phpCAS::client(CAS_VERSION_2_0, 'shib.unl.edu', 443, 'idp/profile/cas');
......@@ -29,7 +34,7 @@ class Auth
}
}
public function requireAuth() : bool
public function requireAuth(): bool
{
$check_auth = phpCAS::checkAuthentication();
if (!$check_auth) {
......@@ -39,41 +44,44 @@ class Auth
return true;
}
public function logout() : bool {
public function logout(): bool
{
if (phpCAS::checkAuthentication()) {
phpCAS::logoutWithRedirectService($this->root_url);
}
return true;
}
public function getUsername() : string
public function getUsername(): string
{
return phpCAS::getUser();
}
public function getUser(): ?Users
{
return $this->doctrine->getRepository(Users::class)->findOneBy(['username' => $this->getUsername()]);
// return $this->doctrine->getRepository(Users::class)->findOneBy(['username' => $this->getUsername()]);
return $this->engine->getUser(userName: $this->getUsername());
}
private function setUser() : int
private function setUser(): int
{
$username = $this->getUsername();
if (empty($username)) {
return 0;
}
# get the user from the DB and do something or something else
$users = $this->doctrine->getRepository(Users::class)->findOneBy(['username' => $username]);
$users = $this->engine->getUser(userName: $username);
if ($users) {
# they exist, no worries
# if they don't have an email, they were created before we had emails in teh system
if (empty($users->getEmail)) {
$info = $this->getUserInfo($username);
$users->setEmail = array_key_exists('email', $info) ? $info['email'] : NULL;
$this->entityManager->persist($users);
}
// if (empty($users->getEmail)) {
// $info = $this->getUserInfo($username);
// $users->setEmail = array_key_exists('email', $info) ? $info['email'] : NULL;
// $this->entityManager->persist($users);
// }
} else {
$info = $this->getUserInfo($username);
# Create a new user
......@@ -81,43 +89,44 @@ class Auth
$user->setUsername($username);
$user->setEmail(array_key_exists('email', $info) ? $info['email'] : NULL);
$user->setDateCreated(new \DateTime());
$user->setName($info['first_name']. " ". $info['last_name']);
$user->setName($info['first_name'] . " " . $info['last_name']);
$this->entityManager->persist($user);
$this->entityManager->flush();
}
$this->entityManager->flush();
return 0;
}
private function getUserInfo($uid) : array
private function getUserInfo($uid): array
{
$info = array();
if (!$json = @file_get_contents($this->directory_url . '?uid=' . $uid . '&format=json')) {
return $info;
}
if (!$json = json_decode($json, true)) {
return $info;
}