Skip to content

Commit

Permalink
Merge pull request #52 from jorisdugue/fix/postgresql-bug
Browse files Browse the repository at this point in the history
Draft: feat(chore): implement usage without user
  • Loading branch information
jorisdugue authored Jan 29, 2024
2 parents 817fba4 + 51e0949 commit 7baa46f
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 47 deletions.
34 changes: 20 additions & 14 deletions Controller/H5PInteractionController.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@ public function setFinished(Request $request, $token): JsonResponse
if (!\H5PCore::validToken('result', $token)) {
\H5PCore::ajaxError('Invalid security token');
}
$result = $this->resultService->handleRequestFinished($request, $this->getUserId($this->getUser()));
$result = $this->resultService->handleRequestFinished(
$request,
$this->h5PIntegration->getUserId($this->getUser())
);
$this->entityManager->persist($result);
$this->entityManager->flush();
return new JsonResponse(['success' => true]);
Expand Down Expand Up @@ -116,7 +119,7 @@ public function contentUserData(Request $request, $contentId, $dataType, $subCon
'subContentId' => $subContentId,
'mainContent' => $contentId,
'dataId' => $dataType,
'user' => $this->getUserId($user),
'user' => $this->h5PIntegration->getUserId($user),
]
);
if (!$update) {
Expand All @@ -125,7 +128,7 @@ public function contentUserData(Request $request, $contentId, $dataType, $subCon
* @var ContentUserData $contentUserData
*/
$contentUserData = new ContentUserData();
$contentUserData->setUser($this->getUserId($user));
$contentUserData->setUser($this->h5PIntegration->getUserId($user));
$contentUserData->setData($data);
$contentUserData->setDataId($dataType);
$contentUserData->setSubContentId($subContentId);
Expand Down Expand Up @@ -153,7 +156,7 @@ public function contentUserData(Request $request, $contentId, $dataType, $subCon
'subContentId' => $subContentId,
'mainContent' => $contentId,
'dataId' => $dataType,
'user' => $this->getUserId($user),
'user' => $this->h5PIntegration->getUserId($user),
]);

//decode for read the information
Expand Down Expand Up @@ -185,7 +188,9 @@ public function embedAction(Request $request, Content $content): Response
$integration = $this->h5PIntegration->getGenericH5PIntegrationSettings();
$content_id_string = 'cid-' . $content->getId();
// Add content specific settings
$integration['contents'][$content_id_string] = $this->h5PIntegration->getH5PContentIntegrationSettings($content);
$integration['contents'][$content_id_string] = $this->h5PIntegration->getH5PContentIntegrationSettings(
$content
);
$preloaded_dependencies = $this->h5PCore->loadContentDependencies($content->getId(), 'preloaded');
$files = $this->h5PCore->getDependenciesFiles($preloaded_dependencies, $this->options->getRelativeH5PPath());
// Load public files
Expand All @@ -206,7 +211,7 @@ public function embedAction(Request $request, Content $content): Response
$lang = $request->getLocale();
$content = [
'id' => $id,
'title' => "H5P Content {$id}",
'title' => "H5P Content $id",
];
//include the embed file (provide in h5p-core)
include $this->kernel->getProjectDir() . '/vendor/h5p/h5p-core/embed.php';
Expand All @@ -215,16 +220,17 @@ public function embedAction(Request $request, Content $content): Response
return new Response($response['#markup']);
}

/**
* Retrieves the URL for the H5P asset based on the configured asset path.
*
* This method generates and returns the URL for the H5P asset by using the
* configured asset path provided through the options service. The URL is
* constructed using the asset path and the Symfony Asset component.
*
* @return string The URL for the H5P asset.
*/
private function getH5PAssetUrl(): string
{
return $this->assetsPaths->getUrl($this->options->getH5PAssetPath());
}

private function getUserId(UserInterface $user)
{
if (method_exists($user, 'getId')) {
return $user->getId();
}
return $user->getUserIdentifier();
}
}
62 changes: 40 additions & 22 deletions Core/H5PSymfony.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

namespace Studit\H5PBundle\Core;

use DateTime;
use DateTimeInterface;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Platforms\PostgreSQLPlatform;
use Doctrine\ORM\EntityManagerInterface;
use GuzzleHttp\Exception\GuzzleException;
use JsonSerializable;
Expand Down Expand Up @@ -35,7 +37,6 @@
use Doctrine\DBAL\Exception\ConnectionException;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;

class H5PSymfony implements \H5PFrameworkInterface
{
Expand Down Expand Up @@ -85,16 +86,17 @@ class H5PSymfony implements \H5PFrameworkInterface
* @param RouterInterface $router
*/
public function __construct(
H5POptions $options,
EditorStorage $editorStorage,
TokenStorageInterface $tokenStorage,
EntityManagerInterface $manager,
?Session $session,
?RequestStack $requestStack,
H5POptions $options,
EditorStorage $editorStorage,
TokenStorageInterface $tokenStorage,
EntityManagerInterface $manager,
?Session $session,
?RequestStack $requestStack,
AuthorizationCheckerInterface $authorizationChecker,
EventDispatcherInterface $eventDispatcher,
RouterInterface $router
) {
EventDispatcherInterface $eventDispatcher,
RouterInterface $router
)
{
$this->options = $options;
$this->editorStorage = $editorStorage;
$this->tokenStorage = $tokenStorage;
Expand Down Expand Up @@ -156,7 +158,8 @@ public function fetchExternalData(
$headers = [],
$files = [],
$method = 'POST'
) {
)
{
$options = [];
if (!empty($data)) {
$options['headers'] = ['Content-Type' => 'application/x-www-form-urlencoded'];
Expand Down Expand Up @@ -890,7 +893,7 @@ public function getOption($name, $default = null)
try {
// return default if db/table still not created
return $this->options->getOption($name, $default);
} catch (ConnectionException | TableNotFoundException $e) {
} catch (ConnectionException|TableNotFoundException $e) {
return $default;
}
}
Expand Down Expand Up @@ -1088,8 +1091,8 @@ public function replaceContentTypeCache($contentTypeCache): void
{
$this->truncateTable(LibrariesHubCache::class);
foreach ($contentTypeCache->contentTypes as $ct) {
$created_at = new \DateTime($ct->createdAt);
$updated_at = new \DateTime($ct->updatedAt);
$created_at = new DateTime($ct->createdAt);
$updated_at = new DateTime($ct->updatedAt);
$cache = new LibrariesHubCache();
$cache->setMachineName($ct->id);
$cache->setMajorVersion($ct->version->major);
Expand Down Expand Up @@ -1118,19 +1121,34 @@ public function replaceContentTypeCache($contentTypeCache): void
}

/**
* @param string $tableClassName
* @throws Exception
* Truncate the specified database table.
*
* This method truncates the given database table by executing SQL queries to temporarily
* disable foreign key checks, truncate the table, and then re-enable foreign key checks.
* Truncating a table removes all rows but keeps the table structure intact.
*
* @param string $tableClassName The fully qualified class name of the entity representing the table.
* @return void
*/
* @throws Exception
* */
private function truncateTable(string $tableClassName): void
{
$cmd = $this->manager->getClassMetadata($tableClassName);
$connection = $this->manager->getConnection();
$dbPlatform = $connection->getDatabasePlatform();
$connection->executeQuery('SET FOREIGN_KEY_CHECKS=0');
$q = $dbPlatform->getTruncateTableSql($cmd->getTableName());
$connection->executeStatement($q);
$connection->executeQuery('SET FOREIGN_KEY_CHECKS=1');
// disable foreign key check or equivalent to pgsql
if ($dbPlatform instanceof PostgreSQLPlatform) {
$connection->executeQuery('SET session_replication_role = replica;');
} else {
$connection->executeQuery('SET FOREIGN_KEY_CHECKS=0');
}
$connection->executeStatement($dbPlatform->getTruncateTableSql($cmd->getTableName()));
// Enable foreign key check
if ($dbPlatform instanceof PostgreSQLPlatform) {
$connection->executeQuery('SET session_replication_role = DEFAULT;');
} else {
$connection->executeQuery('SET FOREIGN_KEY_CHECKS=1');
}
}

/**
Expand Down Expand Up @@ -1164,7 +1182,7 @@ public function getContentHubMetadataChecked($lang = 'en'): ?string
{
// Todo fetch the timestamp of current language here
// dd(Languages::getName($lang));
$date = new \DateTime('now');
$date = new DateTime('now');
return $date->format(DateTimeInterface::RFC7231);
}

Expand Down
17 changes: 13 additions & 4 deletions Core/H5PUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,20 @@ public function getCurrentOrAnonymousUser()
return 'anon.';
}

public function getUserId(UserInterface $user)
/**
* Fetch current User ID
* @param UserInterface|null $user
* @return string|null|integer
*/
public function getUserId(?UserInterface $user)
{
if (method_exists($user, 'getId')) {
return $user->getId();
if ($user !== null) {
if (method_exists($user, 'getId')) {
return $user->getId();
}
return $user->getUserIdentifier();
} else {
return null;
}
return $user->getUserIdentifier();
}
}
11 changes: 7 additions & 4 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@

class Configuration implements ConfigurationInterface
{
const H5P_VERSION = '2.1.0'; // version of Symfony H5P bundle
/**
* version of Symfony H5P bundle
* @return string
*/
const H5P_VERSION = '2.1.0';

/**
* Generates the configuration tree.
*
* @return TreeBuilder|NodeInterface
* @return TreeBuilder
*/
public function getConfigTreeBuilder()
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('studit_h5_p');

Expand Down
7 changes: 4 additions & 3 deletions Entity/Content.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class Content
*/
private $parameters;
/**
* @var string
* @var string|null
*
* @ORM\Column(name="filtered_parameters", type="text", nullable=true)
*/
Expand Down Expand Up @@ -96,10 +96,11 @@ public function getFilteredParameters(): string
{
return $this->filteredParameters;
}

/**
* @param string $filteredParameters
* @param string|null $filteredParameters
*/
public function setFilteredParameters(string $filteredParameters)
public function setFilteredParameters(?string $filteredParameters)
{
$this->filteredParameters = $filteredParameters;
}
Expand Down

0 comments on commit 7baa46f

Please sign in to comment.