user profile, editing and more statistics

This commit is contained in:
Kevin Papst
2016-11-09 21:58:00 +01:00
parent 1678129fe9
commit 8401797728
42 changed files with 1441 additions and 195 deletions

View File

@@ -11,6 +11,10 @@
namespace AppBundle;
use AppBundle\DependencyInjection\AppBundleExtension;
use AppBundle\DependencyInjection\CompilerPass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
@@ -18,7 +22,15 @@ use Symfony\Component\HttpKernel\Bundle\Bundle;
*
* @see http://symfony.com/doc/current/cookbook/bundles/best_practices.html
* @see http://symfony.com/doc/current/best_practices/business-logic.html
*
* @author Kevin Papst <kevin@kevinpapst.de>
*/
class AppBundle extends Bundle
{
}
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new CompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, -1000);
}
}

View File

@@ -11,12 +11,22 @@
namespace AppBundle\Controller;
use AppBundle\Entity\User;
use AppBundle\Form\UserEditType;
use AppBundle\Form\UserPasswordType;
use AppBundle\Repository\UserRepository;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use TimesheetBundle\Entity\Timesheet;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use TimesheetBundle\Model\TimesheetStatistic;
use TimesheetBundle\Repository\TimesheetRepository;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
/**
* User profile controller
@@ -29,45 +39,189 @@ use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
class ProfileController extends Controller
{
/**
* @Route("/", defaults={"ident": null}, name="user_profile")
* @Route("/{ident}/", requirements={"ident": "[a-zA-Z0-9\-].*"}, name="user_profile_ident")
* @Route("/{username}", name="user_profile")
* @Method("GET")
*/
public function indexAction($ident)
public function indexAction($username)
{
$user = $this->getUser();
$user = $this->getUserByUsername($username);
$isAdmin = false;
if ($isAdmin) {
} else {
}
return $this->getProfileView($user);
}
/**
* @param User $user
* @param Form $editForm
* @param Form $pwdForm
* @param string $tab
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function getProfileView(User $user, Form $editForm = null, Form $pwdForm = null, $tab = 'charts')
{
/* @var $timesheetRepo TimesheetRepository */
$timesheetRepo = $this->getDoctrine()->getRepository(Timesheet::class);
$userStats = $timesheetRepo->getUserStatistics($user);
$monthlyStats = $timesheetRepo->getMonthlyStats($user);
// FIXME fetch values dynamically and add trans filter to macros
$items = [
[
'title' => 'Stundenlohn',
'url' => '#',
'color' => 'blue', // aqua, red, green
'value' => 70
],
[
'title' => 'Sprache',
'url' => '#',
'color' => 'green', // aqua, red, green
'value' => 'deutsch'
],
];
$editForm = $editForm !== null ? $editForm : $this->createEditForm($user);
$pwdForm = $pwdForm !== null ? $pwdForm : $this->createPasswordForm($user);
return $this->render(
'user/profile.html.twig',
[
'user' => $this->getUser(),
'settings' => $items,
'stats' => $userStats
'tab' => $tab,
'user' => $user,
'stats' => $userStats,
'years' => $monthlyStats,
'form' => $editForm->createView(),
'form_password' => $pwdForm->createView(),
]
);
}
/**
* @Route("/{username}/edit", name="user_profile_edit")
* @Method({"GET", "POST"})
*/
public function editAction($username, Request $request)
{
$user = $this->getUserByUsername($username);
$editForm = $this->createEditForm($user);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('success', 'action.updated_successfully');
return $this->redirectToRoute(
'user_profile', ['username' => $user->getUsername()]
);
}
return $this->getProfileView($user, $editForm, null, 'profile');
}
/**
* @Route("/{username}/password", name="user_profile_password")
* @Method({"GET", "POST"})
*/
public function passwordAction($username, Request $request)
{
$user = $this->getUserByUsername($username);
$pwdForm = $this->createPasswordForm($user);
$pwdForm->handleRequest($request);
if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('success', 'action.updated_successfully');
return $this->redirectToRoute(
'user_profile', ['username' => $user->getUsername()]
);
}
return $this->getProfileView($user, null, $pwdForm, 'password');
}
/**
* FIXME
* @Route("/{username}/delete", name="user_profile_delete")
* @Method({"GET", "POST"})
*/
public function deleteAction($username, Request $request)
{
$user = $this->getUserByUsername($username);
$deleteForm = $this->createDeleteForm($user);
throw new \Exception('Delete not implemented yet');
}
/**
* @param $username
* @return User
* @throws NotFoundHttpException
*/
protected function getUserByUsername($username)
{
$user = $this->getUser();
// access to own profile always allowed
if (null === $username) {
$username = $user->getUsername();
}
if ($username !== $user->getUsername()) {
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page'); // TODO translation
}
if ($username !== $user->getUsername()) {
/* @var $userRepo UserRepository */
$userRepo = $this->getDoctrine()->getRepository(User::class);
$user = $userRepo->findByUsername($username);
if (null === $user) {
throw new NotFoundHttpException('User "'.$username.'" does not exist');
}
}
return $user;
}
/**
* @param User $user
* @return \Symfony\Component\Form\Form
*/
private function createEditForm(User $user)
{
return $this->createForm(
UserEditType::class,
$user,
[
'action' => $this->generateUrl('user_profile_edit', ['username' => $user->getUsername()]),
'method' => 'POST'
]
);
}
/**
* @param User $user
* @return \Symfony\Component\Form\Form
*/
private function createPasswordForm(User $user)
{
return $this->createForm(
UserPasswordType::class,
$user,
[
'validation_groups' => array('passwordUpdate'),
'action' => $this->generateUrl('user_profile_password', ['username' => $user->getUsername()]),
'method' => 'POST'
]
);
}
/**
* @param User $user
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(User $user)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('user_profile_delete', ['username' => $user->getUsername()]))
->setMethod('DELETE')
->getForm()
;
}
}

View File

@@ -83,47 +83,6 @@ class LoadFixtures implements FixtureInterface, ContainerAwareInterface
$manager->flush();
}
/**
* FIXME CAN BE REMOVED
*
* @param ObjectManager $manager
*/
private function loadPosts(ObjectManager $manager)
{
$authors = [
'anna_admin@example.com',
'tony_teamlead@example.com',
'clara_customer@example.com',
'john_user@example.com'
];
foreach (range(1, 30) as $i) {
$post = new Post();
$post->setTitle($this->getRandomPostTitle());
$post->setSummary($this->getRandomPostSummary());
$post->setSlug($this->container->get('slugger')->slugify($post->getTitle()));
$post->setContent($this->getPostContent());
$post->setAuthorEmail($authors[array_rand($authors, 1)]);
$post->setPublishedAt(new \DateTime('now - '.$i.'days'));
foreach (range(1, 5) as $j) {
$comment = new Comment();
$comment->setAuthorEmail($authors[array_rand($authors, 1)]);
$comment->setPublishedAt(new \DateTime('now + '.($i + $j).'seconds'));
$comment->setContent($this->getRandomCommentContent());
$comment->setPost($post);
$manager->persist($comment);
$post->addComment($comment);
}
$manager->persist($post);
}
$manager->flush();
}
/**
* {@inheritdoc}
*/

View File

@@ -0,0 +1,34 @@
<?php
/*
* This file is part of the Kimai package.
*
* (c) Kevin Papst <kevin@kevinpapst.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AppBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use \Doctrine\Common\ClassLoader;
/**
* Main extension class
*
* @author Kevin Papst <kevin@kevinpapst.de>
*/
class AppExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$rootDir = realpath($container->getParameter('kernel.root_dir'));
$extensionsDir = realpath($rootDir . '/../vendor/beberlei/DoctrineExtensions/src/');
$classLoader = new ClassLoader('DoctrineExtensions', $extensionsDir);
$classLoader->register();
}
}

View File

@@ -0,0 +1,60 @@
<?php
/*
* This file is part of the Kimai package.
*
* (c) Kevin Papst <kevin@kevinpapst.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AppBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\Yaml\Yaml;
/**
* Class Configuration
*
* @author Kevin Papst <kevin@kevinpapst.de>
*/
class CompilerPass implements CompilerPassInterface
{
/**
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
$engine = $container->getParameter('database_engine');
if (null === $engine) {
throw new ParameterNotFoundException('database_engine');
}
$ormConfigDef = $container->getDefinition('doctrine.orm.default_configuration');
$configDir = realpath($container->getParameter('kernel.root_dir') . '/config/');
$config = Yaml::parse(file_get_contents($configDir . '/' . $engine . '.yml'));
if (!isset($config['doctrine']['orm']['dql'])) {
return;
}
$sql = $config['doctrine']['orm']['dql'];
if (!empty($sql)) {
foreach ($sql['string_functions'] as $name => $function) {
$ormConfigDef->addMethodCall('addCustomStringFunction', array($name, $function));
}
foreach ($sql['numeric_functions'] as $name => $function) {
$ormConfigDef->addMethodCall('addCustomNumericFunction', array($name, $function));
}
foreach ($sql['datetime_functions'] as $name => $function) {
$ormConfigDef->addMethodCall('addCustomDatetimeFunction', array($name, $function));
}
}
}
}

View File

@@ -4,7 +4,7 @@ namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User
@@ -28,6 +28,8 @@ class User implements UserInterface
* @var string
*
* @ORM\Column(name="name", type="string", length=160, nullable=false, unique=true)
* @Assert\NotBlank()
* @Assert\Length(min=6, max=160)
*/
private $username;
@@ -35,6 +37,8 @@ class User implements UserInterface
* @var string
*
* @ORM\Column(name="mail", type="string", length=160, nullable=false, unique=true)
* @Assert\NotBlank()
* @Assert\Email()
*/
private $email;
@@ -45,6 +49,14 @@ class User implements UserInterface
*/
private $password;
/**
* @var string
*
* @Assert\NotBlank(groups={"registration", "passwordUpdate"})
* @Assert\Length(min=6, max=4096, groups={"registration", "passwordUpdate"})
*/
private $plainPassword;
/**
* @var string
*
@@ -52,6 +64,13 @@ class User implements UserInterface
*/
private $alias;
/**
* @var string
*
* @ORM\Column(name="language", type="string", length=5, nullable=true)
*/
private $language = 'de';
/**
* @var boolean
*
@@ -62,16 +81,9 @@ class User implements UserInterface
/**
* @var \DateTime
*
* @ORM\Column(name="start_timeframe", type="datetime", nullable=true)
* @ORM\Column(name="registration_date", type="datetime", nullable=true)
*/
private $timeframeBegin;
/**
* @var \DateTime
*
* @ORM\Column(name="end_timeframe", type="datetime", nullable=true)
*/
private $timeframeEnd;
private $registeredAt;
/**
* @var string
@@ -94,6 +106,14 @@ class User implements UserInterface
*/
private $roles = [];
/**
* User constructor.
*/
public function __construct()
{
$this->registeredAt = new \DateTime();
}
/**
* @return int
*/
@@ -103,35 +123,22 @@ class User implements UserInterface
}
/**
* @return string
* @return \DateTime
*/
public function getTimeframeBegin()
public function getRegisteredAt()
{
return $this->timeframeBegin;
return $this->registeredAt;
}
/**
* @param string $timeframeBegin
* @param $registeredAt
* @return $this
*/
public function setTimeframeBegin($timeframeBegin)
public function setRegisteredAt($registeredAt)
{
$this->timeframeBegin = $timeframeBegin;
}
$this->registeredAt = $registeredAt;
/**
* @return string
*/
public function getTimeframeEnd()
{
return $this->timeframeEnd;
}
/**
* @param string $timeframeEnd
*/
public function setTimeframeEnd($timeframeEnd)
{
$this->timeframeEnd = $timeframeEnd;
return $this;
}
/**
@@ -193,6 +200,28 @@ class User implements UserInterface
return $this->password;
}
/**
* Only for form editing, you don't need this method!
*
* @return string
*/
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* Only for form editing, you don't need this method!
*
* @param string $password
* @return $this
*/
public function setPlainPassword($password)
{
$this->plainPassword = $password;
return $this;
}
/**
* @return string
*/
@@ -266,6 +295,22 @@ class User implements UserInterface
return $this;
}
/**
* @return string
*/
public function getLanguage()
{
return $this->language;
}
/**
* @param string $language
*/
public function setLanguage($language)
{
$this->language = $language;
}
/**
* Returns the roles or permissions granted to the user for security.
*

View File

@@ -29,11 +29,18 @@ class NavbarShowUserListener
*/
protected $storage;
/**
* NavbarShowUserListener constructor.
* @param TokenStorageInterface $tokenStorage
*/
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->storage = $tokenStorage;
}
/**
* @param ShowUserEvent $event
*/
public function onShowUser(ShowUserEvent $event)
{
/* @var $myUser User */
@@ -51,8 +58,7 @@ class NavbarShowUserListener
->setIsOnline(true)
->setTitle($myUser->getTitle())
->setAvatar($myUser->getAvatar())
->setMemberSince(new \DateTime()) // FIXME add column to entity
;
->setMemberSince(new \DateTime());
$event->setUser($user);
}

View File

@@ -0,0 +1,67 @@
<?php
/*
* This file is part of the Kimai package.
*
* (c) Kevin Papst <kevin@kevinpapst.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AppBundle\Form;
use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\LanguageType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Defines the form used to create and manipulate Users.
*
* @author Kevin Papst <kevin@kevinpapst.de>
*/
class UserEditType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// string - length 160
->add('alias', null, [
'label' => 'label.alias',
])
// string - length 50
->add('title', null, [
//'attr' => ['autofocus' => true],
'label' => 'label.title',
])
// string - length 160
->add('email', null, [
'label' => 'label.email',
])
// string - length 5
->add('language', LanguageType::class, [
'label' => 'label.language',
'choices' => array('Deutsch' => 'de') // FIXME translation
])
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
'csrf_protection' => true,
'csrf_field_name' => '_token',
'csrf_token_id' => 'edit_user_profile',
]);
}
}

View File

@@ -0,0 +1,55 @@
<?php
/*
* This file is part of the Kimai package.
*
* (c) Kevin Papst <kevin@kevinpapst.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AppBundle\Form;
use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Defines the form used to create and manipulate Users.
*
* @author Kevin Papst <kevin@kevinpapst.de>
*/
class UserPasswordType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('plainPassword', RepeatedType::class, [
'type' => PasswordType::class,
'first_options' => array('label' => 'security.label.password'),
'second_options' => array('label' => 'security.label.password_repeat'),
])
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
'csrf_protection' => true,
'csrf_field_name' => '_token',
'csrf_token_id' => 'edit_user_password',
]);
}
}

View File

@@ -57,7 +57,7 @@ class UserRepository extends EntityRepository
public function findByUsername($username)
{
return $this->findOneBy(['']);
return $this->findOneBy(['username' => $username]);
}
/**