Refactor "save documents" code using the Resources

pull/3904/head
Julio Montoya 4 years ago
parent f4b2e176c6
commit d3d7f5787a
  1. 162
      src/CoreBundle/Controller/Api/BaseResourceFileAction.php
  2. 40
      src/CoreBundle/Controller/Api/CreateDocumentFileAction.php
  3. 100
      src/CoreBundle/Controller/Api/CreateResourceNodeFileAction.php
  4. 29
      src/CoreBundle/Controller/Api/UpdateDocumentFileAction.php
  5. 8
      src/CourseBundle/Entity/CDocument.php

@ -0,0 +1,162 @@
<?php
declare(strict_types=1);
/* For licensing terms, see /license.txt */
namespace Chamilo\CoreBundle\Controller\Api;
use Chamilo\CoreBundle\Entity\AbstractResource;
use Chamilo\CoreBundle\Entity\ResourceLink;
use Chamilo\CourseBundle\Entity\CDocument;
use InvalidArgumentException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class BaseResourceFileAction
{
protected function handleCreateRequest(AbstractResource $resource, Request $request)
{
error_log('handleCreateRequest');
$contentData = $request->getContent();
if (!empty($contentData)) {
$contentData = json_decode($contentData, true);
var_dump($contentData);
$title = $contentData['title'];
$comment = $contentData['comment'];
} else {
$title = $request->get('title');
$comment = $request->get('comment');
}
$fileType = 'folder';
if ($request->request->has('filetype')) {
$fileType = $request->get('filetype');
}
if (empty($fileType)) {
throw new \Exception('filetype needed: folder or file');
}
$nodeId = (int) $request->get('parentResourceNodeId');
if (0 === $nodeId) {
throw new \Exception('parentResourceNodeId int value needed');
}
$resource->setParentResourceNode($nodeId);
switch ($fileType) {
case 'file':
$content = '';
if ($request->request->has('contentFile')) {
$content = $request->request->get('contentFile');
}
$fileParsed = false;
// File upload.
if ($request->files->count() > 0) {
if (!$request->files->has('uploadFile')) {
throw new BadRequestHttpException('"uploadFile" is required');
}
/** @var UploadedFile $uploadedFile */
$uploadedFile = $request->files->get('uploadFile');
$title = $uploadedFile->getClientOriginalName();
$resource->setUploadFile($uploadedFile);
$fileParsed = true;
}
// Get data in content and create a HTML file.
if (!$fileParsed && $content) {
$handle = tmpfile();
fwrite($handle, $content);
$meta = stream_get_meta_data($handle);
$file = new UploadedFile($meta['uri'], $title.'.html', 'text/html', null, true);
$resource->setUploadFile($file);
$fileParsed = true;
}
if (!$fileParsed) {
throw new InvalidArgumentException('filetype was set to "file" but not upload found');
}
break;
case 'folder':
break;
}
if (empty($title)) {
throw new InvalidArgumentException('title required');
}
$resource->setResourceName($title);
}
protected function handleUpdateRequest(AbstractResource $resource, $repo, Request $request)
{
error_log('handleUpdateRequest');
$contentData = $request->getContent();
$resourceLinkList = [];
if (!empty($contentData)) {
error_log('contentData');
$contentData = json_decode($contentData, true);
$title = $contentData['title'];
$content = $contentData['contentFile'];
//$comment = $contentData['comment'] ?? '';
$resourceLinkList = $contentData['resourceLinkListFromEntity'] ?? [];
} else {
$title = $request->get('title');
$content = $request->request->get('contentFile');
//$comment = $request->request->get('comment');
}
$repo->setResourceName($resource, $title);
$hasFile = $resource->getResourceNode()->hasResourceFile();
//if ('file' === $fileType && !empty($content)) {
if ($hasFile && !empty($content)) {
$resourceNode = $resource->getResourceNode();
if ($resourceNode->hasResourceFile()) {
$resourceNode->setContent($content);
$resourceNode->getResourceFile()->setSize(\strlen($content));
}
$resourceNode->setUpdatedAt(new DateTime());
$resourceNode->getResourceFile()->setUpdatedAt(new DateTime());
$resource->setResourceNode($resourceNode);
}
$link = null;
if (!empty($resourceLinkList)) {
foreach ($resourceLinkList as $linkArray) {
// Find the exact link.
$linkId = $linkArray['id'];
/** @var ResourceLink $link */
$link = $resource->getResourceNode()->getResourceLinks()
->filter(
fn ($link) => $link->getId() === $linkId
)->first();
if (null !== $link) {
$link->setVisibility((int) $linkArray['visibility']);
break;
}
}
}
//$isRecursive = 'folder' === $fileType;
$isRecursive = !$hasFile;
// If it's a folder then change the visibility to the children (That have the same link).
if ($isRecursive && null !== $link) {
$repo->copyVisibilityToChildren($resource->getResourceNode(), $link);
}
//$document->setComment($comment);
error_log('Finish update resource node file action');
return $resource;
}
}

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/* For licensing terms, see /license.txt */
namespace Chamilo\CoreBundle\Controller\Api;
use Chamilo\CourseBundle\Entity\CDocument;
use InvalidArgumentException;
use Symfony\Component\HttpFoundation\Request;
class CreateDocumentFileAction extends BaseResourceFileAction
{
public function __invoke(Request $request): CDocument
{
error_log('CreateResourceNodeFileAction __invoke');
$document = new CDocument();
$this->handleCreateRequest($document, $request);
if ($request->request->has('filetype')) {
$document->setFiletype($request->get('filetype'));
}
if ($request->request->has('resourceLinkList')) {
$links = $request->get('resourceLinkList');
$links = false === strpos($links, '[') ? json_decode('['.$links.']', true) : json_decode($links, true);
if (empty($links)) {
$message = 'resourceLinkList is not a valid json. Use for example: [{"c_id":1, "visibility":1}]';
throw new InvalidArgumentException($message);
}
$document->setResourceLinkArray($links);
}
//$document->setComment($comment);
return $document;
}
}

@ -1,100 +0,0 @@
<?php
declare(strict_types=1);
/* For licensing terms, see /license.txt */
namespace Chamilo\CoreBundle\Controller\Api;
use Chamilo\CourseBundle\Entity\CDocument;
use InvalidArgumentException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class CreateResourceNodeFileAction
{
public function __invoke(Request $request): CDocument
{
error_log('CreateResourceNodeFileAction __invoke');
$contentData = $request->getContent();
if (!empty($contentData)) {
$contentData = json_decode($contentData, true);
//error_log(print_r($contentData, 1));
$title = $contentData['title'];
$comment = $contentData['comment'];
} else {
$title = $request->get('title');
$comment = $request->get('comment');
}
$document = new CDocument();
if ($request->request->has('filetype')) {
$document->setFiletype($request->get('filetype'));
}
$nodeId = (int) $request->get('parentResourceNodeId');
$document->setParentResourceNode($nodeId);
switch ($document->getFiletype()) {
case 'file':
$content = '';
if ($request->request->has('contentFile')) {
$content = $request->request->get('contentFile');
}
$fileParsed = false;
// File upload.
if ($request->files->count() > 0) {
if (!$request->files->has('uploadFile')) {
throw new BadRequestHttpException('"uploadFile" is required');
}
/** @var UploadedFile $uploadedFile */
$uploadedFile = $request->files->get('uploadFile');
$title = $uploadedFile->getClientOriginalName();
$document->setUploadFile($uploadedFile);
$fileParsed = true;
}
// Get data in content and create a HTML file.
if (!$fileParsed && $content) {
$handle = tmpfile();
fwrite($handle, $content);
$meta = stream_get_meta_data($handle);
$file = new UploadedFile($meta['uri'], $title.'.html', 'text/html', null, true);
$document->setUploadFile($file);
$fileParsed = true;
}
if (!$fileParsed) {
throw new InvalidArgumentException('filetype was set to "file" but not upload found');
}
break;
case 'folder':
break;
}
if (empty($title)) {
throw new InvalidArgumentException('title required');
}
$document->setTitle($title);
if ($request->request->has('resourceLinkList')) {
$links = $request->get('resourceLinkList');
$links = false === strpos($links, '[') ? json_decode('['.$links.']', true) : json_decode($links, true);
if (empty($links)) {
$message = 'resourceLinkList is not a valid json. Use for example: [{"c_id":1, "visibility":1}]';
throw new InvalidArgumentException($message);
}
$document->setResourceLinkArray($links);
}
$document->setComment($comment);
return $document;
}
}

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/* For licensing terms, see /license.txt */
namespace Chamilo\CoreBundle\Controller\Api;
use Chamilo\CoreBundle\Entity\ResourceLink;
use Chamilo\CourseBundle\Entity\CDocument;
use Chamilo\CourseBundle\Repository\CDocumentRepository;
use DateTime;
use Symfony\Component\HttpFoundation\Request;
class UpdateDocumentFileAction extends BaseResourceFileAction
{
public function __invoke(CDocument $document, Request $request, CDocumentRepository $repo): CDocument
{
error_log('UpdateDocumentFileAction __invoke');
$this->handleUpdateRequest($document, $repo, $request);
//$document->setComment($comment);
error_log('Finish update resource node file action');
return $document;
}
}

@ -11,8 +11,8 @@ use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\OrderFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
use ApiPlatform\Core\Serializer\Filter\PropertyFilter;
use Chamilo\CoreBundle\Controller\Api\CreateResourceNodeFileAction;
use Chamilo\CoreBundle\Controller\Api\UpdateResourceNodeFileAction;
use Chamilo\CoreBundle\Controller\Api\UpdateDocumentFileAction;
use Chamilo\CoreBundle\Controller\Api\CreateDocumentFileAction;
use Chamilo\CoreBundle\Entity\AbstractResource;
use Chamilo\CoreBundle\Entity\ResourceInterface;
use Chamilo\CourseBundle\Traits\ShowCourseResourcesInSessionTrait;
@ -27,7 +27,7 @@ use Symfony\Component\Validator\Constraints as Assert;
* denormalizationContext={"groups"={"document:write"}},
* itemOperations={
* "put" ={
* "controller"=UpdateResourceNodeFileAction::class,
* "controller"=UpdateDocumentFileAction::class,
* "deserialize"=false,
* "security" = "is_granted('EDIT', object.resourceNode)",
* "validation_groups"={"media_object_create", "document:write"},
@ -41,7 +41,7 @@ use Symfony\Component\Validator\Constraints as Assert;
* },
* collectionOperations={
* "post"={
* "controller"=CreateResourceNodeFileAction::class,
* "controller"=CreateDocumentFileAction::class,
* "deserialize"=false,
* "security"="is_granted('ROLE_CURRENT_COURSE_TEACHER') or is_granted('ROLE_CURRENT_COURSE_SESSION_TEACHER')",
* "validation_groups"={"Default", "media_object_create", "document:write"},

Loading…
Cancel
Save