Commit bcebadc5 by Krzysztof Kuźniar

Bundle init

parents
<?php
namespace Webkul\TableAttributeBundle\ArrayConverter\FlatToStandard;
use Pim\Component\Catalog\Repository\LocaleRepositoryInterface;
use Pim\Component\Connector\ArrayConverter\ArrayConverterInterface;
use Pim\Component\Connector\ArrayConverter\FieldsRequirementChecker;
use Pim\Component\Connector\Exception\StructureArrayConversionException;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* Convert flat format to standard format for attribute column
*
* @author Jitendra Singh <jitendra@webkul.com>
* @copyright Webkul Software Pvt Ltd (https://www.webkul.com)
*/
class AttributeColumn implements ArrayConverterInterface
{
/** @var LocaleRepositoryInterface */
protected $localeRepository;
/** @var FieldsRequirementChecker */
protected $fieldChecker;
/**
* @param LocaleRepositoryInterface $localeRepository
* @param FieldsRequirementChecker $fieldChecker
*/
public function __construct(
LocaleRepositoryInterface $localeRepository,
FieldsRequirementChecker $fieldChecker
) {
$this->localeRepository = $localeRepository;
$this->fieldChecker = $fieldChecker;
}
/**
* {@inheritdoc}
*
* Converts flat csv array to standard structured array:
*
* Before:
* {
* 'attribute': 'maximum_print_size',
* 'code': '210_x_1219_mm',
* 'sort_order': '2',
* 'type': text,
* 'validations': '{0: "email", 1: "required"}',
* 'options': null,
* 'label-de_DE': '210 x 1219 mm',
* 'label-en_US': '210 x 1219 mm',
* 'label-fr_FR': '210 x 1219 mm'
* }
*
* After:
* {
* 'attribute': 'maximum_print_size',
* 'code': '210_x_1219_mm',
* 'sort_order': 2,
* 'type': text,
* 'validations': {
* 0: "email",
* 1: "required"
* },
* 'options': null,
* 'labels': {
* 'de_DE': '210 x 1219 mm',
* 'en_US': '210 x 1219 mm',
* 'fr_FR': '210 x 1219 mm'
* }
* }
*/
public function convert(array $item, array $options = [])
{
$this->validate($item);
$convertedItem = ['labels' => []];
foreach ($item as $field => $data) {
$isLabel = false !== strpos($field, 'label-', 0);
if ($isLabel) {
$labelTokens = explode('-', $field);
$labelLocale = $labelTokens[1];
$convertedItem['labels'][$labelLocale] = $data;
} else {
if (in_array($field, ['validations', 'options'])) {
$convertedItem[$field] = json_decode($data, true);
} else {
$convertedItem[$field] = $data;
}
}
}
if (isset($convertedItem['sort_order'])) {
$convertedItem['sort_order'] = (int) $convertedItem['sort_order'];
}
return $convertedItem;
}
/**
* @param array $item
*
* @throws StructureArrayConversionException
*/
protected function validate(array $item)
{
$requiredFields = ['attribute', 'code'];
$this->fieldChecker->checkFieldsPresence($item, $requiredFields);
$authorizedFields = array_merge($requiredFields, ['sort_order', 'type', 'validations', 'options']);
$localeCodes = $this->localeRepository->getActivatedLocaleCodes();
foreach ($localeCodes as $code) {
$authorizedFields[] = 'label-' . $code;
}
foreach (array_keys($item) as $field) {
if (!in_array($field, $authorizedFields)) {
throw new StructureArrayConversionException(
sprintf(
'Field "%s" is provided, authorized fields are: "%s"',
$field,
implode(', ', $authorizedFields)
)
);
}
}
}
}
<?php
namespace Webkul\DamBundle\ArrayConverter\FlatToStandard\Product\ValueConverter;
use Webkul\DamBundle\Entity\Asset;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* Converts a table value from Akeneo PIM flat format to Akeneo PIM standard format
*
* Here is an example with the temperature attribute.
* Flat format:
* [
* 'my-table' => "column_1=>Column 1 Row 1 Value&column_2=>Column 2 Row 1 Value|column_1=>Column 1 Row 2 Value&column_2=>Column 2 Row 2 Value",
* ]
*
* Standard format:
* [
* 'my-table' => [{
* "locale": "en_US",
* "scope": null,
* "data": [{
* "column_1": "Column 1 Row 1 Value",
* "column_2": "Column 2 Row 1 Value"
* }, {
* "column_1": "Column 1 Row 2 Value",
* "column_2": "Column 2 Row 2 Value"
* }
* ]
* }]
* ]
*
* @author Jitendra Singh <jitendra@webkul.com>
* @copyright Webkul Software Pvt Ltd (https://www.webkul.com)
*/
class AssetConverter implements \ValueConverterInterface_F2S
{
/** @var string[] */
protected $supportedFieldTypes;
protected $em;
/**
* @param string[] $supportedFieldTypes
*/
public function __construct(array $supportedFieldTypes, \Doctrine\ORM\EntityManager $em)
{
$this->supportedFieldTypes = $supportedFieldTypes;
$this->em = $em;
}
/**
* {@inheritdoc}
*/
public function supportsField($attributeType)
{
return in_array($attributeType, $this->supportedFieldTypes);
}
/**
* {@inheritdoc}
*/
public function convert(array $attributeFieldInfo, $value)
{
if ('' === trim($value)) {
$data = null;
} else {
$data = [];
$rowArray = explode('|', $value);
foreach ($rowArray as $key => $row) {
# column_1=>Column 1 Row 1 Value&column_2=>Column 2 Row 1 Value
$columnArray = explode('&', $row);
foreach ($columnArray as $column) {
# column_1=>Column 1 Row 1 Value
$value = explode('=>', $column);
if ($value[0] == 'code') {
$data[] = $value[1];
}
}
}
}
return [
$attributeFieldInfo['attribute']->getCode() => [[
'locale' => $attributeFieldInfo['locale_code'],
'scope' => $attributeFieldInfo['scope_code'],
'data' => $data,
]],
];
}
}
<?php
namespace Webkul\TableAttributeBundle\ArrayConverter\StandardToFlat;
use Pim\Component\Connector\ArrayConverter\ArrayConverterInterface;
use Pim\Component\Connector\ArrayConverter\StandardToFlat\AbstractSimpleArrayConverter;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* Convert standard format to flat format for attribute column
*
* @author Jitendra Singh <jitendra@webkul.com>
* @copyright Webkul Software Pvt Ltd (https://www.webkul.com)
*/
class AttributeColumn extends AbstractSimpleArrayConverter implements ArrayConverterInterface
{
/**
* {@inheritdoc}
*/
protected function convertProperty($property, $data, array $convertedItem, array $options)
{
switch ($property) {
case 'labels':
foreach ($data as $localeCode => $label) {
$labelKey = sprintf('label-%s', $localeCode);
$convertedItem[$labelKey] = $label;
}
break;
case 'validations':
case 'options':
$convertedItem[$property] = json_encode($data);
break;
default:
$convertedItem[$property] = (string) $data;
}
return $convertedItem;
}
}
<?php
namespace Webkul\DamBundle\ArrayConverter\StandardToFlat\Product\ValueConverter;
use Webkul\DamBundle\Entity\Asset;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* Converts a asset value from Akeneo PIM standard format to Akeneo PIM flat format
*
* Standard format:
* [
* 'my-asset' => [{
* "locale": "en_US",
* "scope": null,
* "data": [
* "firstasset",
* "secondassetmodule"
* ]
* }]
* ]
*
* Here is an example with the my-asset attribute.
* Flat format:
* [
* "my-asset" => "code=>firstasset&description=>asset&starred=>1&title=>First Asset&alt=>Asset&medias=>/tmp/pim/file_storage/b/9/7/e//b97e8e0c10a7daffefa87a05aaf8931cb4436a99/images.jpeg|code=>secondasset&description=>dsadasd&starred=>&title=>wew&alt=>wdasds&medias=>/tmp/pim/file_storage/9/3/a/a//93aa7b1917dcba0d8a418fdcfd4c193bc1f9b303/download.png"
* ]
*
* @author Aman Srivastava <aman.srivastava462@webkul.com>
* @copyright Webkul Software Pvt Ltd (https://www.webkul.com)
*/
class AssetConverter extends \AbstractValueConverter
{
protected $em;
/** @var AttributeColumnsResolver */
protected $columnsResolver;
/** @var array */
protected $supportedAttributeTypes;
protected $fileExporterPath;
public function __construct(
\AttributeColumnsResolver $columnsResolver,
array $supportedAttributeTypes,
\Doctrine\ORM\EntityManager $em
) {
parent::__construct($columnsResolver, $supportedAttributeTypes);
$this->em = $em;
}
/**
* {@inheritdoc}
*/
/**
* Converts a value
*
* @param string $attributeCode
* @param mixed $data
*
* @return array
*/
public function convert($attributeCode, $data)
{
$convertedItem = [];
foreach ($data as $value) {
$flatName = $this->columnsResolver->resolveFlatAttributeName(
$attributeCode,
$value['locale'],
$value['scope']
);
$arrayValues = !empty($value['data']) ? $value['data'] : [];
$columnArray = [];
foreach ($arrayValues as $row) {
$rows = $this->getSingleArrayResultByCode($row);
if (!is_array($rows) && empty($rows)) {
continue;
}
$rowArray = [];
$imageArray = [];
foreach ($rows as $key => $value) {
if (gettype($value) == 'string') {
$rowArray[] = $key . '=>' .$value;
} elseif (gettype($value) == 'array') {
if ($this->isAssoc($value)) {
$rowArray[] = $key . '=>' . $value['filePath'];
} else {
$imagePath = [];
foreach ($value as $images) {
$imagePath[] = isset($images['filePath'])? $images['filePath'] : null;
}
$rowArray[] = $key . '=>' . implode("!", $imagePath);
}
} elseif (gettype($value) == 'boolean') {
$rowArray[] = $key . '=>' .$value;
}
}
$columnArray[] = implode('&', $rowArray);
}
$convertedItem[$flatName] = implode('|', $columnArray);
}
return $convertedItem;
}
public function getSingleArrayResultByCode($identifier)
{
// dump($identifier);
$result = $this->em->createQueryBuilder()
->select('a, m')
->from('WebkulDamBundle:Asset', 'a')
->leftJoin('a.medias', 'm')
->where('a.code = :identifier')
->setParameter('identifier', $identifier)
->getQuery()->getArrayResult();
// dump($result);
$result = count($result) !== 0 ? $result[0] : null;
if (isset($result['medias']) && count($result['medias']) === 1) {
$result['medias'] = reset($result['medias']);
}
// dump($result);
return $result;
}
public function isAssoc(array $arr)
{
if (array() === $arr) {
return false;
}
return array_keys($arr) !== range(0, count($arr) - 1);
}
}
<?php
namespace Webkul\DamBundle\AttributeType;
/**
* attribute types dictionary
*
*/
final class DamAssetAttributeTypes
{
const DAM_ASSETS = 'pim_catalog_asset_group';
const BACKEND_TYPE_TEXT_COLLECTION = 'dam_assets';
}
<?php
namespace Webkul\DamBundle\AttributeType;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* Table attribute type
*
*/
class DamAssetType extends \AbstractAttributeType
{
/**
* {@inheritdoc}
*/
public function getName()
{
return DamAssetAttributeTypes::DAM_ASSETS;
}
}
<?php
namespace Webkul\DamBundle\Classes\Constraints;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Constraint;
class UniqueCode extends Constraint
{
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
public function validatedBy()
{
return 'uniqueAssetCode';
}
public $message = 'This Code value is already used.';
}
<?php
namespace Webkul\DamBundle\Classes\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Validation;
class UniqueCodeValidator extends ConstraintValidator
{
private $repo;
public function __construct($repo = null)
{
$this->repo = $repo;
}
public function validate($asset, Constraint $constraint)
{
$qb = $this->repo->createQueryBuilder('a');
$expr = $qb->expr();
if ($asset->getId()) {
$qb->Andwhere('a.id'.' != :id');
$qb->setParameter('id', $asset->getId());
}
$qb->Andwhere('a.code'.' = :code');
$qb->setParameter('code', $type->getCode());
$result = $qb->getQuery()->getResult();
if (count($result)) {
$this->context->buildViolation($constraint->message)
->atPath('code')
->addViolation();
}
}
}
<?php
namespace Webkul\DamBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\EntityManagerInterface;
use Webkul\DamBundle\Entity\AssetCategory;
class AddCategoryCommand extends ContainerAwareCommand
{
/** @var EntityManager */
protected $em;
public function __construct(
$em
) {
$this->em = $em;
parent::__construct();
}
protected function configure()
{
parent::configure();
$this->setName('dam:asset:category')
->setDescription('add Master Category');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
//remove from routing.yml
$em = $this->em;
$repo = $em->getRepository('WebkulDamBundle:AssetCategory');
$field = $repo->findOneBy([
'code' => 'master_asset'
]);
if(!$field) {
$field = new AssetCategory();
$field->setCode('master_asset');
$field->setLevel('0');
$field->setRight('2');
$field->setLeft('1');
$em->persist($field);
$em->flush();
}
$output->writeln("Dam module has been successfully Installed.");
}
}
\ No newline at end of file
<?php
namespace Webkul\DamBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Command\Command;
// ContainerAwareCommand
class DamInstallationCommand extends Command
{
protected static $defaultName = 'wk_dam:setup:install';
protected function configure()
{
$this->setName('wk_dam:setup:install')
->setDescription('Install Dam Akeneo Connector module setup')
->setHelp('setups Dam Akeneo Connector bundle installation');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$errorFlag = false;
/* version wise loading */
if (class_exists('Pim\Bundle\CatalogBundle\Version')) {
// version 2
$versionClass = new \Pim\Bundle\CatalogBundle\Version();
} elseif (class_exists('Akeneo\Platform\CommunityVersion')) {
// version 3 or later
$versionClass = new \Akeneo\Platform\CommunityVersion();
}
$version = $versionClass::VERSION;
$this->updateLessFile($version);
if ($version >= "4.0") {
$this->runAkeneo4DamInstallationCommand($input, $output);
} else {
$this->runAkeneoDamInstallationCommand($input, $output);
}
return 0;
}
protected function runAkeneo4DamInstallationCommand(InputInterface $input, OutputInterface $output)
{
shell_exec('rm -rf public/bundles public/js');
$this->runCommand(
'pim:installer:assets',
[
'--clean' => null,
'--symlink' => null,
],
$output
);
$this->runCommand(
'doctrine:schema:update',
[
'--force' => null,
],
$output
);
shell_exec('rm -rf public/css');
shell_exec('yarnpkg run less');
shell_exec('rm -rf public/dist-dev');
shell_exec('yarnpkg run webpack-dev');
shell_exec('rm -rf public/dist');
shell_exec('yarnpkg run webpack');
}
protected function runAkeneoDamInstallationCommand(InputInterface $input, OutputInterface $output)
{
$this->runCommand(
'pim:install:asset',
[
'--env' => 'prod',
],
$output
);
$this->runCommand(
'assets:install',
[
'--symlink' => null,
'--relative' => null,
],
$output
);
$this->runCommand(
'doctrine:schema:update',
[
'--force' => null,
],
$output
);
shell_exec('yarn run webpack');
}
protected function runCommand($name, array $args, $output)
{
$command = $this->getApplication()->find($name);
$commandInput = new ArrayInput(
$args
);
$command->run($commandInput, $output);
}
protected function updateLessFile($version)
{
$location = __DIR__.'/../Resources/public/less/index.less';
if (!is_writable($location)) {
throw new \Exception(sprintf('%s file is not writable, provide the write permission', $location));
}
$conf = file_get_contents($location);
if ($version >= "4.0") {
$searchValue = './web';
$replaceValue = './public';
} else {
$searchValue = './public';
$replaceValue = './web';
}
$value = str_replace($searchValue, $replaceValue, $conf);
file_put_contents($location, $value);
}
}
<?php
namespace Webkul\DamBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Console\Input\InputOption;
class ExpiredCommand extends ContainerAwareCommand
{
/** @var EntityManager */
protected $em;
public function __construct(
$em
) {
$this->em = $em;
parent::__construct();
}
protected function configure()
{
parent::configure();
$this->setName('dam:asset:check-expire')
->setDescription('Check Expired Dam Module')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Force deletion');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$removeAssetCount = 0;
$io->title("Check Expired Dam Module");
$force = $input->getOption('force');
if (!$force) {
$io->note('Command running in safe mode. Use --force to delete assets.');
}
$io->writeln('Searching assets...');
$assets = $this->getContainer()->get('webkul_dam.repository.asset')->findAll();
$output->writeln(sprintf('Found %d Assets', count($assets)));
$removed = 0;
foreach ($assets as $asset) {
$defaultTimeZone = $asset->getDefaultTimezone() ? : 'UTC';
date_default_timezone_set($defaultTimeZone);
$currentDate = date("Y-m-d");
$dateToBeExpired = $asset->getExpirationDate() ? : null;
if ($dateToBeExpired) {
if (strtotime($currentDate) >= strtotime($dateToBeExpired)) {
if ($force) {
foreach ($asset->getMedias() as $media) {
$this->em->remove($media);
}
$this->em->remove($asset);
$this->em->flush();
$removed++;
}
$removeAssetCount++;
}
}
}
$io->writeln(sprintf('Found %d Expired Asset, Removed %s', $removeAssetCount, $removed));
$io->success("Checked all expired Assets.");
}
}
<?php
namespace Webkul\DamBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\EntityManagerInterface;
class UninstallCommand extends ContainerAwareCommand
{
/** @var attributeRepository */
protected $attributeRepository;
/** @var EntityManager */
protected $em;
public function __construct(
$attributeRepository,
$em
) {
$this->attributeRepository = $attributeRepository;
$this->em = $em;
parent::__construct();
}
protected function configure()
{
parent::configure();
$this->setName('dam:asset:uninstall')
->setDescription('Unistall Dam Module');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
//remove from routing.yml
$damAttributes = $this->attributeRepository
->findBy(['type'=>'pim_catalog_asset_group']);
if (!empty($damAttributes)) {
$em = $this->em;
foreach ($damAttributes as $damAttribute) {
$em->remove($damAttribute);
}
$em->flush();
}
if (class_exists('Pim\Bundle\CatalogBundle\Version')) {
// version 2
$versionClass = new \Pim\Bundle\CatalogBundle\Version();
} elseif (class_exists('Akeneo\Platform\CommunityVersion')) {
// version 3 or later
$versionClass = new \Akeneo\Platform\CommunityVersion();
}
$version = $versionClass::VERSION;
$this->removeFromRouting($version);
$this->removeFromAppKernel($version);
$output->writeln("Dam module has been successfully uninstalled.");
}
protected function removeFromRouting($version)
{
if($version > '4.0') {
$routeFile = $this->getContainer()->get('kernel')->getProjectDir() . '/config/routes/webkul_dambundle.yml';
$search = "WebkulDamBundle/Resources/config/routing.yml";
$lines = file($routeFile);
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== false) ? $key + 1 : $line_number;
}
} else {
$routeFile = $this->getContainer()->get('kernel')->getRootDir() . '/config/routing.yml';
$search = "WebkulDamBundle/Resources/config/routing.yml";
$lines = file($routeFile);
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== false) ? $key + 1 : $line_number;
}
}
if ($line_number) {
$delete_from_line = $line_number - 1;
$delete_to_line = $line_number + 1;
$this->deleteLineFromFile($delete_from_line, $delete_to_line, $routeFile);
}
}
protected function removeFromAppKernel($version)
{
if($version > '4.0') {
$fileName = $this->getContainer()->get('kernel')->getProjectDir() . '/config/bundles.php';
$search = "Webkul\DamBundle\WebkulDamBundle::class => ['all' => true]";
$lines = file($fileName);
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== false) ? $key + 1 : $line_number;
}
} else {
$fileName = $this->getContainer()->get('kernel')->getRootDir() . '/AppKernel.php';
$search = "new Webkul\DamBundle\WebkulDamBundle()";
$lines = file($fileName);
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== false) ? $key + 1 : $line_number;
}
}
if ($line_number) {
$delete_from_line = $line_number;
$delete_to_line = $line_number;
$this->deleteLineFromFile($delete_from_line, $delete_to_line, $fileName);
}
}
protected function deleteLineFromFile($from, $to, $fileName)
{
exec('sed -i.bak ' . $from . ',' . $to . 'd ' . $fileName);
exec('rm -rf '.$fileName. '.bak');
}
}
<?php
declare(strict_types=1);
namespace Webkul\DamBundle\Completeness;
use Akeneo\Pim\Structure\Component\AttributeTypes;
use Akeneo\Pim\Enrichment\Component\Product\Completeness\MaskItemGenerator\MaskItemGeneratorForAttributeType;
class DefaultMaskItemGenerator implements MaskItemGeneratorForAttributeType
{
public function forRawValue(string $attributeCode, string $channelCode, string $localeCode, $value): array
{
return [
sprintf(
'%s-%s-%s',
$attributeCode,
$channelCode,
$localeCode
)
];
}
public function supportedAttributeTypes(): array
{
return [
'pim_catalog_asset_group'
];
}
}
<?php
namespace Webkul\DamBundle\Component;
class TempStoragePathProvider
{
protected $tempStoragePath;
protected $container;
public function __construct($container)
{
$this->container = $container;
$this->setTempStoragePath();
}
public function getTempStoragePath()
{
return $this->tempStoragePath;
}
public function setTempStoragePath()
{
$this->tempStoragePath = sys_get_temp_dir();
if ($this->container->hasParameter('tmp_storage_dir')) {
$this->tempStoragePath = $this->container->getParameter('tmp_storage_dir');
}
}
}
<?php
namespace Webkul\DamBundle\Connector\ArrayConvertor\FlatToStandard;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* Convert flat format to standard format for asset
*
* @author Ankit yadav <ankit.yadav726@webkul.com>
* @copyright 2010-2018 Webkul (http://www.webkul.com)
*/
class Asset implements \ArrayConverterInterface
{
/** @var FieldsRequirementChecker */
protected $fieldChecker;
/** @var array */
protected $booleanFields;
/**
* @param FieldsRequirementChecker $fieldChecker
* @param array $booleanFields
*/
public function __construct(\FieldsRequirementChecker $fieldChecker, array $booleanFields)
{
$this->fieldChecker = $fieldChecker;
$this->booleanFields = $booleanFields;
}
/**
* {@inheritdoc}
*
* Converts flat array to standard structured array:
*
* Flat Format of Dam Data
* [
* "code" => "code",
* "media" => [
* "/tmp/dummy1.jpg",
* "/tmp/dummy2.jpg",
* ]
* "alt" => "alt",
* "created_at" => "created_date",
* "descriptions" => "descriptions"
* "tags" => tag1 & tag2 & tag3 & tag4,
* "categories" => category1 & category2 & category3 & category4,
* ]
*
*
*/
public function convert(array $item, array $options = [])
{
if (empty($item['code'])) {
if (!empty($item['media'])) {
$item['code'] = $this->getCodeFromUrl($item['media'][0]);
}
}
$this->fieldChecker->checkFieldsPresence($item, ['code']);
$this->fieldChecker->checkFieldsFilling($item, ['code']);
$convertedItem = [];
foreach ($item as $field => $data) {
$convertedItem = $this->convertFields($field, $this->booleanFields, $data, $convertedItem);
}
// unset($convertedItem['alt']);
// unset($convertedItem['created_at']);
// unset($convertedItem['updated_at']);
// unset($convertedItem['description']);
return $convertedItem;
}
/**
* @param string $field
* @param array $booleanFields
* @param array $data
* @param array $convertedItem
*
* @return array
*/
protected function convertFields($field, $booleanFields, $data, $convertedItem)
{
if (false !== strpos($field, 'label-', 0)) {
$labelTokens = explode('-', $field);
$labelLocale = $labelTokens[1];
$convertedItem['labels'][$labelLocale] = $data;
} elseif ('number_min' === $field ||
'number_max' === $field ||
'max_file_size'=== $field
) {
$convertedItem[$field] = $this->convertFloat($data);
} elseif ('sort_order' === $field ||
'max_characters' === $field ||
'minimum_input_length'=== $field
) {
$convertedItem[$field] = ('' === $data) ? null : (int) $data;
} elseif ('options' === $field ||
'available_locales' === $field ||
'allowed_extensions' === $field
) {
$convertedItem[$field] = ('' === $data) ? [] : explode(',', $data);
} elseif ('created_at' === $field ||
'updated_at'=== $field
) {
$convertedItem[$field] = $this->convertDate($data);
} elseif (in_array($field, $booleanFields, true) && '' !== $data) {
$convertedItem[$field] = (bool) $data;
} elseif (gettype($data) == 'array') {
$convertedItem[$field] = $data;
} elseif ('' !== $data) {
$convertedItem[$field] = (string) $data;
} else {
$convertedItem[$field] = null;
}
return $convertedItem;
}
/**
* @param mixed $number
*
* @return string|null
*/
protected function convertFloat($number)
{
if ('' === $number || null === $number) {
return null;
}
if (is_numeric($number)) {
return number_format($number, 4, '.', '');
}
return $number;
}
/**
* Return the value if it's not a date (launch an exception should not be done here).
* "2015-12-31" will be converted to "2015-12-31T00:00:00+01:00"
*
* These dates are wrong and will not converted:
* "2015/12/31"
* "2015-45-31"
* "not a date"
*
* @param mixed $date
*
* @return string|null
*/
protected function convertDate($date)
{
if ('' === $date || null === $date) {
return null;
}
$datetime = \DateTime::createFromFormat('Y-m-d', $date);
$errors = \DateTime::getLastErrors();
if (0 === $errors['warning_count'] && 0 === $errors['error_count']) {
$datetime->setTime(0, 0, 0);
return $datetime->format('c');
}
return $date;
}
/**
* WIP
* @param string $url
*
* @return string|null
*/
protected function getCodeFromUrl($url)
{
$tail = explode('/', $url);
return end($tail);
}
}
<?php
namespace Webkul\DamBundle\Connector\Reader;
use Webkul\DamBundle\Repository\AssetRepository;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* AttributeColumn reader sorted by attribute and sort order.
*
* @author Jitendra Singh <jitendra@webkul.com>
* @copyright Webkul Software Pvt Ltd (https://www.webkul.com)
*/
class AssetReader extends \AbstractReader implements
\ItemReaderInterface,
\InitializableInterface,
\StepExecutionAwareInterface
{
/** @var AttributeColumnRepositoryInterface */
protected $repository;
/**
* @param AttributeColumnRepositoryInterface $repository
*/
public function __construct(AssetRepository $repository)
{
$this->repository = $repository;
}
/**
* {@inheritdoc}
*/
protected function getResults()
{
$data = new \ArrayIterator($this->repository->findBy([], ['code' => 'ASC', 'starred' => 'ASC']));
return $data;
}
}
<?php
namespace Webkul\DamBundle\Connector\Reader\Import;
use Webkul\DamBundle\Services\DamServices;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* Csv reader
*
* @author Aman Srivastava <aman.srivastava462@webkul.com>
* @copyright 2019 Webkul Software Pvt. Ltd. (https://webkul.com)
*/
class AssetReader implements \FileReaderInterface
{
/** @var FileIteratorFactory */
protected $fileIteratorFactory;
/** @var ArrayConverterInterface */
protected $converter;
/** @var FileIteratorInterface */
protected $fileIterator;
/** @var StepExecution */
protected $stepExecution;
/** @var array */
protected $options;
protected $damService;
/**
* @param FileIteratorFactory $fileIteratorFactory
* @param ArrayConverterInterface $converter
* @param array $options
*/
public function __construct(
\FileIteratorFactory $fileIteratorFactory,
\ArrayConverterInterface $converter,
DamServices $damService,
array $options = []
) {
$this->fileIteratorFactory = $fileIteratorFactory;
$this->converter = $converter;
$this->options = $options;
$this->damService = $damService;
}
/**
* {@inheritdoc}
*/
public function read()
{
$jobParameters = $this->stepExecution->getJobParameters();
$filePath = $jobParameters->get('filePath');
if (null === $this->fileIterator) {
$delimiter = $jobParameters->get('delimiter');
$enclosure = $jobParameters->get('enclosure');
$defaultOptions = [
'reader_options' => [
'fieldDelimiter' => $delimiter,
'fieldEnclosure' => $enclosure,
],
];
$this->fileIterator = $this->fileIteratorFactory->create(
$filePath,
array_merge($defaultOptions, $this->options)
);
$this->fileIterator->rewind();
}
$this->fileIterator->next();
if ($this->fileIterator->valid() && null !== $this->stepExecution) {
$this->stepExecution->incrementSummaryInfo('item_position');
}
$data = $this->fileIterator->current();
if (null === $data) {
return null;
}
$headers = $this->fileIterator->getHeaders();
$countHeaders = count($headers);
$countData = count($data);
$this->checkColumnNumber($countHeaders, $countData, $data, $filePath);
if ($countHeaders > $countData) {
$missingValuesCount = $countHeaders - $countData;
$missingValues = array_fill(0, $missingValuesCount, '');
$data = array_merge($data, $missingValues);
}
$item = array_combine($this->fileIterator->getHeaders(), $data);
if(!isset($item['media'])){
$headers = explode(',', $this->fileIterator->getHeaders()[0]);
$data = explode(',', $data[0]);
$item = array_combine($headers, $data);
}
$mediavalues = explode("&", $item['media']);
$code = isset($item['code']) ? $item['code'] : null;
$item['media'] = $this->damService->transform($mediavalues, $this->fileIterator->getDirectoryPath(), $code);
try {
$item = $this->converter->convert($item, $this->getArrayConverterOptions());
} catch (\DataArrayConversionException $e) {
$this->skipItemFromConversionException($item, $e);
}
return $item;
}
/**
* {@inheritdoc}
*/
public function setStepExecution(\StepExecution $stepExecution)
{
$this->stepExecution = $stepExecution;
}
/**
* {@inheritdoc}
*/
public function flush()
{
$this->fileIterator = null;
}
/**
* Returns the options for array converter. It can be overridden in the sub classes.
*
* @return array
*/
protected function getArrayConverterOptions()
{
return [];
}
/**
* @param array $item
* @param DataArrayConversionException $exception
*
* @throws \InvalidItemException
* @throws InvalidItemFromViolationsException
*/
protected function skipItemFromConversionException(array $item, \DataArrayConversionException $exception)
{
if (null !== $this->stepExecution) {
$this->stepExecution->incrementSummaryInfo('skip');
}
if (null !== $exception->getViolations()) {
throw new \InvalidItemFromViolationsException(
$exception->getViolations(),
new \FileInvalidItem($item, ($this->stepExecution->getSummaryInfo('item_position'))),
[],
0,
$exception
);
}
$invalidItem = new \FileInvalidItem(
$item,
($this->stepExecution->getSummaryInfo('item_position'))
);
throw new \InvalidItemException($exception->getMessage(), $invalidItem, [], 0, $exception);
}
/**
* @param int $countHeaders
* @param int $countData
* @param string $data
* @param string $filePath
*
* @throws \InvalidItemException
*/
protected function checkColumnNumber($countHeaders, $countData, $data, $filePath)
{
if ($countHeaders < $countData) {
throw new \InvalidItemException(
'pim_connector.steps.file_reader.invalid_item_columns_count',
new \FileInvalidItem($data, ($this->stepExecution->getSummaryInfo('item_position'))),
[
'%totalColumnsCount%' => $countHeaders,
'%itemColumnsCount%' => $countData,
'%filePath%' => $filePath,
'%lineno%' => $this->fileIterator->key()
]
);
}
}
}
<?php
namespace Webkul\DamBundle\Connector\Writer;
use Webkul\WebkulCsvBundle\Services\WebkulCsvConnector;
use Webkul\WebkulCsvBundle\DataFormatter\CsvDataFormat;
use Webkul\DamBundle\Services\DamServices;
use Symfony\Component\Finder\Finder;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
class AssetWriter extends \AbstractItemMediaWriter implements
\ItemWriterInterface,
\InitializableInterface,
\FlushableInterface,
\StepExecutionAwareInterface,
\ArchivableWriterInterface
{
/** @var ArrayConverterInterface */
protected $arrayConverter;
/** @var FlatItemBufferFlusher */
protected $flusher;
/** @var BufferFactory */
protected $bufferFactory;
/** @var AttributeRepositoryInterface */
protected $attributeRepository;
/** @var FileExporterPathGeneratorInterface */
protected $fileExporterPath;
/** @var string[] */
protected $mediaAttributeTypes;
/** @var ConnectorService */
protected $connectorService;
/** @var String */
protected $jobParamFilePath;
protected $headerAttr;
protected $damService;
protected $filesystemProvider;
public function __construct(
\ArrayConverterInterface $arrayConverter,
\BufferFactory $bufferFactory,
\FlatItemBufferFlusher $flusher,
\AttributeRepositoryInterface $attributeRepository,
\FileExporterPathGeneratorInterface $fileExporterPath,
array $mediaAttributeTypes,
DamServices $damService,
\FilesystemProvider $filesystemProvider,
\FileFetcherInterface $mediaFetcher
) {
parent::__construct($arrayConverter, $bufferFactory, $flusher, $attributeRepository, $fileExporterPath, $mediaAttributeTypes);
$this->fileExporterPath = $fileExporterPath;
$this->damService = $damService;
$this->filesystemProvider = $filesystemProvider;
$this->mediaFetcher = $mediaFetcher;
}
/**
* {@inheritdoc}
*/
protected function getWriterConfiguration()
{
$parameters = $this->stepExecution->getJobParameters();
return [
'type' => 'csv',
'fieldDelimiter' => $parameters->get('delimiter'),
'fieldEnclosure' => $parameters->get('enclosure'),
'shouldAddBOM' => false,
];
}
/**
* {@inheritdoc}
*/
protected function getItemIdentifier(array $asset)
{
return $asset['code'];
}
/**
* {@inheritdoc}
*/
public function write(array $items)
{
$parameters = $this->stepExecution->getJobParameters();
$converterOptions = $this->getConverterOptions($parameters);
$flatItems = [];
$directory = $this->stepExecution->getJobExecution()->getExecutionContext()
->get(\JobInterface::WORKING_DIRECTORY_PARAMETER);
foreach ($items as $item) {
if ($parameters->has('with_media') && $parameters->get('with_media')) {
$item = $this->resolveMediaPaths($item, $directory);
}
$convertedArray = $this->resolveAttributeMediaPaths($item, $directory);
$flatItems[] = $convertedArray;
}
$parameters = $this->stepExecution->getJobParameters();
$options = [];
$options['withHeader'] = $parameters->get('withHeader');
$this->flatRowBuffer->write($flatItems, $options);
}
protected function resolveAttributeMediaPaths($item, $tmpDirectory)
{
$media = [];
$i = 1;
foreach ($item['media'] as $mediaItem) {
$identifier = $this->getItemIdentifier($item);
if (null !== $mediaItem['filePath']) {
$exportDirectory = $this->fileExporterPath->generate(
[
'locale' => '',
'scope' => ''
],
[
'identifier' => $identifier,
'code' => 'media_'.$i,
]
);
$imagename = $mediaItem['original_file_name'];
$filesystem = $this->filesystemProvider->getFilesystem('catalogStorage');
$mediafiles = str_replace('/tmp/pim/file_storage/', '', $mediaItem['filePath']);
$this->mediaFetcher->fetch(
$filesystem,
$mediafiles,
['filePath'=>$tmpDirectory . $exportDirectory,
'filename' => $imagename ]
);
$finder = new Finder();
if (is_dir($tmpDirectory . $exportDirectory)) {
$files = iterator_to_array($finder->files()->in($tmpDirectory . $exportDirectory));
if (!empty($files)) {
$path = $exportDirectory . current($files)->getFilename();
$this->writtenFiles[$tmpDirectory . $path] = $path;
$media[] = preg_replace('#/+#', '/', $path);
}
}
}
$i++;
}
$stringConvert = implode("&", $media);
$item['media'] = $stringConvert;
return $item;
}
}
<?php
namespace Webkul\DamBundle\Connector\Writer;
use Webkul\WebkulCsvBundle\Services\WebkulCsvConnector;
use Webkul\WebkulCsvBundle\DataFormatter\CsvDataFormat;
use Webkul\DamBundle\Services\DamServices;
use Symfony\Component\Finder\Finder;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
class ProductModelWriter extends \AbstractItemMediaWriter implements
\ItemWriterInterface,
\InitializableInterface,
\FlushableInterface,
\StepExecutionAwareInterface,
\ArchivableWriterInterface
{
/** @var ArrayConverterInterface */
protected $arrayConverter;
/** @var FlatItemBufferFlusher */
protected $flusher;
/** @var BufferFactory */
protected $bufferFactory;
/** @var AttributeRepositoryInterface */
protected $attributeRepository;
/** @var FileExporterPathGeneratorInterface */
protected $fileExporterPath;
/** @var string[] */
protected $mediaAttributeTypes;
/** @var ConnectorService */
protected $connectorService;
/** @var String */
protected $jobParamFilePath;
protected $headerAttr;
protected $damService;
protected $filesystemProvider;
public function __construct(
\ArrayConverterInterface $arrayConverter,
\BufferFactory $bufferFactory,
\FlatItemBufferFlusher $flusher,
\AttributeRepositoryInterface $attributeRepository,
\FileExporterPathGeneratorInterface $fileExporterPath,
array $mediaAttributeTypes,
DamServices $damService,
\FilesystemProvider $filesystemProvider,
\FileFetcherInterface $mediaFetcher
) {
parent::__construct($arrayConverter, $bufferFactory, $flusher, $attributeRepository, $fileExporterPath, $mediaAttributeTypes);
$this->fileExporterPath = $fileExporterPath;
$this->damService = $damService;
$this->filesystemProvider = $filesystemProvider;
$this->mediaFetcher = $mediaFetcher;
}
/**
* {@inheritdoc}
*/
protected function getWriterConfiguration()
{
$parameters = $this->stepExecution->getJobParameters();
return [
'type' => 'csv',
'fieldDelimiter' => $parameters->get('delimiter'),
'fieldEnclosure' => $parameters->get('enclosure'),
'shouldAddBOM' => false,
];
}
/**
* {@inheritdoc}
*/
protected function getItemIdentifier(array $productModel)
{
return $productModel['code'];
}
/**
* {@inheritdoc}
*/
public function write(array $items)
{
$parameters = $this->stepExecution->getJobParameters();
$converterOptions = $this->getConverterOptions($parameters);
$flatItems = [];
$directory = $this->stepExecution->getJobExecution()->getExecutionContext()
->get(\JobInterface::WORKING_DIRECTORY_PARAMETER);
foreach ($items as $item) {
if ($parameters->has('with_media') && $parameters->get('with_media')) {
$item = $this->resolveMediaPaths($item, $directory);
}
$convertedArray = $this->arrayConverter->convert($item, $converterOptions);
$newConvertedArray = $this->resolveAttributeMediaPaths($convertedArray, $item, $directory);
$flatItems[] = $newConvertedArray;
}
$parameters = $this->stepExecution->getJobParameters();
$options = [];
$options['withHeader'] = $parameters->get('withHeader');
$this->flatRowBuffer->write($flatItems, $options);
}
protected function resolveAttributeMediaPaths($convertedArray = [], $item, $tmpDirectory)
{
foreach ($convertedArray as $convertedKey => $convertedValue) {
if (!in_array($convertedKey, $this->damService->getAssetAttributeCodes())) {
continue;
}
$newConvertedArray = [];
$attributeArrays = explode("|", $convertedValue);
foreach ($attributeArrays as $attributeArray) {
$imageArray = json_decode('{"' . str_replace('=>', '":"', str_replace("&", '","', $attributeArray)) .'"}', true);
$identifier = $this->getItemIdentifier($item);
$allMediaFiles = isset($imageArray['medias']) ? explode('!', $imageArray['medias']) : [];
$tempPath = [];
$tempConvertArray = [];
foreach ($allMediaFiles as $imagePath) {
if (null !== $imagePath) {
$imagename = pathinfo($imagePath);
$imagename = explode('_', $imagename['basename']);
$tmpDir = array_shift($imagename);
$imagename = implode('_', $imagename);
$exportDirectory = $this->fileExporterPath->generate(
[
'locale' => '',
'scope' => ''
],
[
'identifier' => $identifier,
'code' => $imageArray['code'] .'/'. $tmpDir
]
);
$filesystem = $this->filesystemProvider->getFilesystem('catalogStorage');
$mediafiles = str_replace('/tmp/pim/file_storage/', '', $imagePath);
$this->mediaFetcher->fetch(
$filesystem,
$mediafiles,
['filePath'=>$tmpDirectory . $exportDirectory,
'filename' => $imagename ]
);
$finder = new Finder();
if (is_dir($tmpDirectory . $exportDirectory)) {
$files = iterator_to_array($finder->files()->in($tmpDirectory . $exportDirectory));
if (!empty($files)) {
$path = $exportDirectory . current($files)->getFilename();
$this->writtenFiles[$tmpDirectory . $path] = $path;
$tempPath[] = preg_replace('#/+#', '/', $path);
$imageArray['medias'] = implode('!', $tempPath);
$convertedPath = str_replace("\\", "", json_encode($imageArray));
$tempConvertArray = str_replace(
'"}',
'',
str_replace(
'{"',
'',
str_replace(
'":"',
'=>',
str_replace('","', "&", $convertedPath)
)
)
);
}
}
}
}
$newConvertedArray[] = $tempConvertArray;
}
$stringConvert = implode("|", $newConvertedArray);
$convertedArray[$convertedKey] = $stringConvert;
}
return $convertedArray;
}
}
<?php
namespace Webkul\DamBundle\Connector\Writer;
use Webkul\WebkulCsvBundle\Services\WebkulCsvConnector;
use Webkul\WebkulCsvBundle\DataFormatter\CsvDataFormat;
use Webkul\DamBundle\Services\DamServices;
use Symfony\Component\Finder\Finder;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
class ProductWriter extends \AbstractItemMediaWriter implements
\ItemWriterInterface,
\InitializableInterface,
\FlushableInterface,
\StepExecutionAwareInterface,
\ArchivableWriterInterface
{
/** @var ArrayConverterInterface */
protected $arrayConverter;
/** @var FlatItemBufferFlusher */
protected $flusher;
/** @var BufferFactory */
protected $bufferFactory;
/** @var AttributeRepositoryInterface */
protected $attributeRepository;
/** @var FileExporterPathGeneratorInterface */
protected $fileExporterPath;
/** @var string[] */
protected $mediaAttributeTypes;
/** @var ConnectorService */
protected $connectorService;
/** @var String */
protected $jobParamFilePath;
protected $headerAttr;
protected $damService;
protected $filesystemProvider;
public function __construct(
\ArrayConverterInterface $arrayConverter,
\BufferFactory $bufferFactory,
\FlatItemBufferFlusher $flusher,
\AttributeRepositoryInterface $attributeRepository,
\FileExporterPathGeneratorInterface $fileExporterPath,
array $mediaAttributeTypes,
DamServices $damService,
\FilesystemProvider $filesystemProvider,
\FileFetcherInterface $mediaFetcher
) {
parent::__construct($arrayConverter, $bufferFactory, $flusher, $attributeRepository, $fileExporterPath, $mediaAttributeTypes);
$this->fileExporterPath = $fileExporterPath;
$this->damService = $damService;
$this->filesystemProvider = $filesystemProvider;
$this->mediaFetcher = $mediaFetcher;
}
/**
* {@inheritdoc}
*/
protected function getWriterConfiguration()
{
$parameters = $this->stepExecution->getJobParameters();
return [
'type' => 'csv',
'fieldDelimiter' => $parameters->get('delimiter'),
'fieldEnclosure' => $parameters->get('enclosure'),
'shouldAddBOM' => false,
];
}
/**
* {@inheritdoc}
*/
protected function getItemIdentifier(array $product)
{
return $product['identifier'];
}
/**
* {@inheritdoc}
*/
public function write(array $items)
{
$parameters = $this->stepExecution->getJobParameters();
$converterOptions = $this->getConverterOptions($parameters);
$flatItems = [];
$directory = $this->stepExecution->getJobExecution()->getExecutionContext()
->get(\JobInterface::WORKING_DIRECTORY_PARAMETER);
foreach ($items as $item) {
if ($parameters->has('with_media') && $parameters->get('with_media')) {
$item = $this->resolveMediaPaths($item, $directory);
}
$convertedArray = $this->arrayConverter->convert($item, $converterOptions);
$newConvertedArray = $this->resolveAttributeMediaPaths($convertedArray, $item, $directory);
$flatItems[] = $newConvertedArray;
}
$parameters = $this->stepExecution->getJobParameters();
$options = [];
$options['withHeader'] = $parameters->get('withHeader');
$this->flatRowBuffer->write($flatItems, $options);
}
protected function resolveAttributeMediaPaths($convertedArray = [], $item, $tmpDirectory)
{
foreach ($convertedArray as $convertedKey => $convertedValue) {
if (!in_array($convertedKey, $this->damService->getAssetAttributeCodes())) {
continue;
}
$newConvertedArray = [];
$attributeArrays = explode("|", $convertedValue);
foreach ($attributeArrays as $attributeArray) {
$imageArray = json_decode('{"' . str_replace('=>', '":"', str_replace("&", '","', $attributeArray)) .'"}', true);
$identifier = $this->getItemIdentifier($item);
$allMediaFiles = isset($imageArray['medias']) ? explode('!', $imageArray['medias']) : [];
$tempPath = [];
$tempConvertArray = [];
foreach ($allMediaFiles as $imagePath) {
if (null !== $imagePath) {
$imagename = pathinfo($imagePath);
$imagename = explode('_', $imagename['basename']);
$tmpDir = array_shift($imagename);
$imagename = implode('_', $imagename);
$exportDirectory = $this->fileExporterPath->generate(
[
'locale' => '',
'scope' => ''
],
[
'identifier' => $identifier,
'code' => $imageArray['code'] .'/'. $tmpDir
]
);
$filesystem = $this->filesystemProvider->getFilesystem('catalogStorage');
$mediafiles = str_replace('/tmp/pim/file_storage/', '', $imagePath);
$this->mediaFetcher->fetch(
$filesystem,
$mediafiles,
['filePath'=>$tmpDirectory . $exportDirectory,
'filename' => $imagename ]
);
$finder = new Finder();
if (is_dir($tmpDirectory . $exportDirectory)) {
$files = iterator_to_array($finder->files()->in($tmpDirectory . $exportDirectory));
if (!empty($files)) {
$path = $exportDirectory . current($files)->getFilename();
$this->writtenFiles[$tmpDirectory . $path] = $path;
$tempPath[] = preg_replace('#/+#', '/', $path);
$imageArray['medias'] = implode('!', $tempPath);
$convertedPath = str_replace("\\", "", json_encode($imageArray));
$tempConvertArray = str_replace(
'"}',
'',
str_replace(
'{"',
'',
str_replace(
'":"',
'=>',
str_replace('","', "&", $convertedPath)
)
)
);
}
}
}
}
$newConvertedArray[] = $tempConvertArray;
}
$stringConvert = implode("|", $newConvertedArray);
$convertedArray[$convertedKey] = $stringConvert;
}
return $convertedArray;
}
}
<?php
/*
* This file is part of the Akeneo Dam Module.
*
* (c) 2019 Webkul Soft. Pvt. Ltd. (https://webkul.com)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Webkul\DamBundle\Context\Akeneo3;
use Webkul\DamBundle\AttributeType\DamAssetAttributeTypes;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Pim\Bundle\UserBundle\Entity\User;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* User context that provides access to user locale, channel and default category tree
*
* @author Aman Srivastava <aman.srivastava462@webkul.com>
*/
class UserContext extends \BaseUserContext
{
/** @var string */
protected $treeOptionKey;
/**
* @param TokenStorageInterface $tokenStorage
* @param LocaleRepositoryInterface $localeRepository
* @param ChannelRepositoryInterface $channelRepository
* @param CategoryRepositoryInterface $categoryRepository
* @param RequestStack $requestStack
* @param ChoicesBuilderInterface $choicesBuilder
* @param AuthorizationCheckerInterface $authorizationChecker
* @param CategoryAccessRepository $categoryAccessRepo
* @param string $defaultLocale
* @param string $treeOptionKey
*/
public function __construct(
TokenStorageInterface $tokenStorage,
\LocaleRepositoryInterface $localeRepository,
\ChannelRepositoryInterface $channelRepository,
\CategoryRepositoryInterface $categoryRepository,
RequestStack $requestStack,
$defaultLocale,
$treeOptionKey
) {
parent::__construct(
$tokenStorage,
$localeRepository,
$channelRepository,
$categoryRepository,
$requestStack,
$defaultLocale
);
$this->treeOptionKey = $treeOptionKey;
}
/**
* Returns the current locale making sure that user has permissions for this locale
*
* @throws \LogicException When there is no granted locale
*
* @return LocaleInterface
*/
public function getCurrentGrantedLocale()
{
$locale = $this->getRequestLocale();
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = $this->getSessionLocale();
}
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = $this->getUserLocale();
}
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = $this->getDefaultLocale();
}
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = current($this->getGrantedUserLocales());
$locale = (false === $locale) ? null : $locale;
}
if (null === $locale) {
throw new \LogicException("User doesn't have access to any activated locales");
}
if (null !== $this->getCurrentRequest() && $this->getCurrentRequest()->hasSession()) {
$this->getCurrentRequest()->getSession()->set('dataLocale', $locale->getCode());
$this->getCurrentRequest()->getSession()->save();
}
return $locale;
}
/**
* Returns active locales the user has access to
*
* @param string $permissionLevel
*
* @return LocaleInterface[]
*/
public function getGrantedUserLocales($permissionLevel = Attributes::VIEW_ITEMS)
{
return array_filter(
$this->getUserLocales(),
function ($locale) use ($permissionLevel) {
return $this->authorizationChecker->isGranted($permissionLevel, $locale);
}
);
}
/**
* Get accessible user category tree
*
* @throws \LogicException
*
* @return CategoryInterface
*/
public function getAccessibleUserTree()
{
$defaultTree = $this->getUserOption($this->treeOptionKey);
if ($defaultTree) {
return $defaultTree;
}
$grantedCategoryIds = $this->getGrantedCategories();
$grantedTrees = $this->categoryRepository->getGrantedTrees($grantedCategoryIds);
if (!empty($grantedTrees)) {
return current($grantedTrees);
}
throw new \LogicException('User should have a default product tree');
}
/**
* Get the default tree
*
* @return CategoryInterface
*/
public function getDefaultTree()
{
$defaultTree = $this->getUserOption($this->treeOptionKey);
return $defaultTree;
}
/**
* Get granted categories
*
* @return int[]
*/
public function getGrantedCategories()
{
$user = $this->getUser();
if (null === $user) {
return [];
}
return $this->categoryRepository->getGrantedCategoryIds($user, DamAssetAttributeTypes::DAM_ASSETS);
}
/**
* Get user product category tree
*
* @return CategoryInterface
*/
public function getUserProductCategoryTree(): \CategoryInterface
{
$defaultTree = $this->getUserOption($this->treeOptionKey);
return $defaultTree ?: current($this->categoryRepository->getTrees());
}
}
<?php
/*
* This file is part of the Akeneo Dam Module.
*
* (c) 2019 Webkul Soft. Pvt. Ltd. (https://webkul.com)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Webkul\DamBundle\Context;
use Webkul\DamBundle\AttributeType\DamAssetAttributeTypes;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Pim\Bundle\UserBundle\Entity\User;
// use Pim\Bundle\CatalogBundle\Builder\ChoicesBuilderInterface;
/**
* User context that provides access to user locale, channel and default category tree
*
* @author Aman Srivastava <aman.srivastava462@webkul.com>
*/
class UserContext extends \BaseUserContext
{
/** @var string */
protected $treeOptionKey;
/**
* @param TokenStorageInterface $tokenStorage
* @param LocaleRepositoryInterface $localeRepository
* @param ChannelRepositoryInterface $channelRepository
* @param CategoryRepositoryInterface $categoryRepository
* @param RequestStack $requestStack
* @param //ChoicesBuilderInterface $choicesBuilder
* @param AuthorizationCheckerInterface $authorizationChecker
* @param CategoryAccessRepository $categoryAccessRepo
* @param string $defaultLocale
* @param string $treeOptionKey
*/
public function __construct(
TokenStorageInterface $tokenStorage,
\LocaleRepositoryInterface $localeRepository,
\ChannelRepositoryInterface $channelRepository,
\CategoryRepositoryInterface $categoryRepository,
RequestStack $requestStack,
//ChoicesBuilderInterface $choicesBuilder,
$defaultLocale,
$treeOptionKey
) {
parent::__construct(
$tokenStorage,
$localeRepository,
$channelRepository,
$categoryRepository,
$requestStack,
//$choicesBuilder,
$defaultLocale
);
$this->treeOptionKey = $treeOptionKey;
}
/**
* Returns the current locale making sure that user has permissions for this locale
*
* @throws \LogicException When there is no granted locale
*
* @return LocaleInterface
*/
public function getCurrentGrantedLocale()
{
$locale = $this->getRequestLocale();
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = $this->getSessionLocale();
}
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = $this->getUserLocale();
}
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = $this->getDefaultLocale();
}
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = current($this->getGrantedUserLocales());
$locale = (false === $locale) ? null : $locale;
}
if (null === $locale) {
throw new \LogicException("User doesn't have access to any activated locales");
}
if (null !== $this->getCurrentRequest() && $this->getCurrentRequest()->hasSession()) {
$this->getCurrentRequest()->getSession()->set('dataLocale', $locale->getCode());
$this->getCurrentRequest()->getSession()->save();
}
return $locale;
}
/**
* Returns active locales the user has access to
*
* @param string $permissionLevel
*
* @return LocaleInterface[]
*/
public function getGrantedUserLocales($permissionLevel = Attributes::VIEW_ITEMS)
{
return array_filter(
$this->getUserLocales(),
function ($locale) use ($permissionLevel) {
return $this->authorizationChecker->isGranted($permissionLevel, $locale);
}
);
}
/**
* Get accessible user category tree
*
* @throws \LogicException
*
* @return CategoryInterface
*/
public function getAccessibleUserTree()
{
$defaultTree = $this->getUserOption($this->treeOptionKey);
if ($defaultTree) {
return $defaultTree;
}
$grantedCategoryIds = $this->getGrantedCategories();
$grantedTrees = $this->categoryRepository->getGrantedTrees($grantedCategoryIds);
if (!empty($grantedTrees)) {
return current($grantedTrees);
}
throw new \LogicException('User should have a default product tree');
}
/**
* Get the default tree
*
* @return CategoryInterface
*/
public function getDefaultTree()
{
$defaultTree = $this->getUserOption($this->treeOptionKey);
return $defaultTree;
}
/**
* Get granted categories
*
* @return int[]
*/
public function getGrantedCategories()
{
$user = $this->getUser();
if (null === $user) {
return [];
}
return $this->categoryRepository->getGrantedCategoryIds($user, DamAssetAttributeTypes::DAM_ASSETS);
}
/**
* Get user product category tree
*
* @return CategoryInterface
*/
public function getUserProductCategoryTree(): \CategoryInterface
{
$defaultTree = $this->getUserOption($this->treeOptionKey);
return $defaultTree ?: current($this->categoryRepository->getTrees());
}
}
<?php
/*
* This file is part of the Akeneo Dam Module.
*
* (c) 2019 Webkul Soft. Pvt. Ltd. (https://webkul.com)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Webkul\DamBundle\Context;
use Webkul\DamBundle\AttributeType\DamAssetAttributeTypes;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Pim\Bundle\UserBundle\Entity\User;
use Pim\Bundle\CatalogBundle\Builder\ChoicesBuilderInterface;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* User context that provides access to user locale, channel and default category tree
*
* @author Aman Srivastava <aman.srivastava462@webkul.com>
*/
class UserContext extends \BaseUserContext
{
/** @var string */
protected $treeOptionKey;
/**
* @param TokenStorageInterface $tokenStorage
* @param LocaleRepositoryInterface $localeRepository
* @param ChannelRepositoryInterface $channelRepository
* @param CategoryRepositoryInterface $categoryRepository
* @param RequestStack $requestStack
* @param ChoicesBuilderInterface $choicesBuilder
* @param AuthorizationCheckerInterface $authorizationChecker
* @param CategoryAccessRepository $categoryAccessRepo
* @param string $defaultLocale
* @param string $treeOptionKey
*/
public function __construct(
TokenStorageInterface $tokenStorage,
\LocaleRepositoryInterface $localeRepository,
\ChannelRepositoryInterface $channelRepository,
\CategoryRepositoryInterface $categoryRepository,
RequestStack $requestStack,
ChoicesBuilderInterface $choicesBuilder,
$defaultLocale,
$treeOptionKey
) {
parent::__construct(
$tokenStorage,
$localeRepository,
$channelRepository,
$categoryRepository,
$requestStack,
$choicesBuilder,
$defaultLocale
);
$this->treeOptionKey = $treeOptionKey;
}
/**
* Returns the current locale making sure that user has permissions for this locale
*
* @throws \LogicException When there is no granted locale
*
* @return LocaleInterface
*/
public function getCurrentGrantedLocale()
{
$locale = $this->getRequestLocale();
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = $this->getSessionLocale();
}
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = $this->getUserLocale();
}
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = $this->getDefaultLocale();
}
if (null === $locale || !$this->authorizationChecker->isGranted(Attributes::VIEW_ITEMS, $locale)) {
$locale = current($this->getGrantedUserLocales());
$locale = (false === $locale) ? null : $locale;
}
if (null === $locale) {
throw new \LogicException("User doesn't have access to any activated locales");
}
if (null !== $this->getCurrentRequest() && $this->getCurrentRequest()->hasSession()) {
$this->getCurrentRequest()->getSession()->set('dataLocale', $locale->getCode());
$this->getCurrentRequest()->getSession()->save();
}
return $locale;
}
/**
* Returns active locales the user has access to
*
* @param string $permissionLevel
*
* @return LocaleInterface[]
*/
public function getGrantedUserLocales($permissionLevel = Attributes::VIEW_ITEMS)
{
return array_filter(
$this->getUserLocales(),
function ($locale) use ($permissionLevel) {
return $this->authorizationChecker->isGranted($permissionLevel, $locale);
}
);
}
/**
* Get accessible user category tree
*
* @throws \LogicException
*
* @return CategoryInterface
*/
public function getAccessibleUserTree()
{
$defaultTree = $this->getUserOption($this->treeOptionKey);
if ($defaultTree) {
return $defaultTree;
}
$grantedCategoryIds = $this->getGrantedCategories();
$grantedTrees = $this->categoryRepository->getGrantedTrees($grantedCategoryIds);
if (!empty($grantedTrees)) {
return current($grantedTrees);
}
throw new \LogicException('User should have a default product tree');
}
/**
* Get the default tree
*
* @return CategoryInterface
*/
public function getDefaultTree()
{
$defaultTree = $this->getUserOption($this->treeOptionKey);
return $defaultTree;
}
/**
* Get granted categories
*
* @return int[]
*/
public function getGrantedCategories()
{
$user = $this->getUser();
if (null === $user) {
return [];
}
return $this->categoryRepository->getGrantedCategoryIds($user, DamAssetAttributeTypes::DAM_ASSETS);
}
/**
* Get user product category tree
*
* @return CategoryInterface
*/
public function getUserProductCategoryTree(): \CategoryInterface
{
$defaultTree = $this->getUserOption($this->treeOptionKey);
return $defaultTree ?: current($this->categoryRepository->getTrees());
}
}
<?php
namespace Webkul\DamBundle\Controller;
use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;
use Pim\Component\Catalog\Model\ProductInterface;
use Webkul\DamBundle\Repository\AssetCategoryRepository;
use Webkul\DamBundle\Repository\AssetRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* Asset category controller
*
* @author Aman Srivastava <aman.srivastava462@webkul.com>
* @copyright 2019 Webkul Software Pvt. Ltd (http://www.webkul.com)
*/
class AssetCategoryController
{
/** @var AssetRepository */
protected $assetRepository;
/** @var AssetCategoryRepository*/
protected $assetCategoryRepository;
/** @var ObjectFilterInterface */
protected $objectFilter;
/** @var UserContext */
protected $userContext;
/**
* @param AssetRepository $productRepository
* @param AssetCategoryRepository $productCategoryRepository
* @param ObjectFilterInterface $objectFilter
*/
public function __construct(
AssetRepository $productRepository,
AssetCategoryRepository $productCategoryRepository,
\ObjectFilterInterface $objectFilter,
\BaseUserContext $userContext
) {
$this->productRepository = $productRepository;
$this->productCategoryRepository = $productCategoryRepository;
$this->objectFilter = $objectFilter;
$this->userContext = $userContext;
}
/**
* List categories and trees for a product
*
* @param string $id
*
* @AclAncestor("webkul_dam_configuration")
*
* @return JsonResponse
*/
public function listAction($id)
{
$product = $this->findProductOr404($id);
$trees = $this->productCategoryRepository->getItemCountByTrees($product);
$alltree = [];
foreach ($trees as $tree) {
$tree['tree']->setLocale($this->userContext->getCurrentLocaleCode());
$alltree[] = $tree;
}
$result['trees'] = $this->buildTrees($trees);
$result['categories'] = $this->buildCategories($product);
return new JsonResponse($result);
}
/**
* Find a product by its id or return a 404 response
*
* @param string $id the product id
*
* @throws NotFoundHttpException
*
* @return ProductInterface
*/
protected function findProductOr404($id)
{
$product = $this->productRepository->find($id);
if (!$product) {
throw new NotFoundHttpException(
sprintf('Product with id %s could not be found.', (string) $id)
);
}
return $product;
}
/**
* @param array $trees
*
* @return array
*/
protected function buildTrees(array $trees)
{
$result = [];
foreach ($trees as $tree) {
$category = $tree['tree'];
if (!$this->objectFilter->filterObject($category, 'pim.internal_api.product_category.view')) {
$result[] = [
'id' => $category->getId(),
'code' => $category->getCode(),
'label' => $category->getLabel(),
'associated' => $tree['itemCount'] > 0
];
}
}
return $result;
}
/**
* @param ProductInterface $product
*
* @return array
*/
protected function buildCategories($product)
{
$result = [];
foreach ($product->getCategory() as $category) {
$result[] = [
'id' => $category->getId(),
'code' => $category->getCode(),
'rootId' => $category->getRoot(),
];
}
return $result;
}
}
<?php
namespace Webkul\DamBundle\Controller;
use Webkul\DamBundle\Repository\AssetCategoryRepository;
use Webkul\DamBundle\Repository\AssetRepository;
use Doctrine\Common\Collections\Collection;
use Oro\Bundle\SecurityBundle\SecurityFacade;
use Pim\Component\Catalog\Model\CategoryInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Doctrine\Common\Collections\ArrayCollection;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* Controller used to render categories of an entity (like assets).
*
* @author Aman Srivastava <aman.srivastava462@webkul.com>
* @copyright 2018 Webkul Soft. Pvt. Ltd. (http://www.webkul.com)
*/
class AssetCategoryListController extends Controller
{
/** @var AssetRepository */
protected $productRepository;
/** @var AssetsCategoryRepository */
protected $categoryRepository;
/** @var SecurityFacade */
protected $securityFacade;
/** @var string */
protected $categoryClass;
/** @var string */
protected $acl;
/** @var string */
protected $template;
/** @var UserContext */
protected $userContext;
/**
* @param AssetsCategoryRepository $categoryRepository
* @param SecurityFacade $securityFacade
* @param string $categoryClass
* @param string $acl
* @param string $template
*/
public function __construct(
\BaseUserContext $userContext,
AssetRepository $productRepository,
AssetCategoryRepository $categoryRepository,
string $categoryClass,
SecurityFacade $securityFacade,
string $acl,
string $template
) {
$this->userContext = $userContext;
$this->productRepository = $productRepository;
$this->categoryRepository = $categoryRepository;
$this->categoryClass = $categoryClass;
$this->securityFacade = $securityFacade;
$this->acl = $acl;
$this->template = $template;
}
/**
* List categories associated with the provided product and descending from the category
* defined by the parent parameter.
*
* @param Request $request The request object
* @param string $id Product id
* @param int $categoryId The parent category id
*
* httpparam include_category if true, will include the parentCategory in the response
*
* @return Response
*/
public function listCategoriesAction(Request $request, $id, $categoryId)
{
$entityWithCategories = $this->findEntityWithCategoriesOr404($id);
$category = $this->categoryRepository->find($categoryId);
$category->setLocale($this->userContext->getCurrentLocaleCode());
if (null === $category) {
throw new NotFoundHttpException(sprintf('%s category not found', $this->categoryClass));
}
$categories = null;
$selectedCategoryIds = $request->get('selected', null);
if (null !== $selectedCategoryIds) {
$categories = $this->categoryRepository->getCategoriesByIds($selectedCategoryIds);
foreach ($categories as $res) {
$res->setLocale($this->userContext->getCurrentLocaleCode());
}
$categories = new ArrayCollection($categories);
} elseif (null !== $entityWithCategories) {
$categories = $entityWithCategories->getCategories();
}
$trees = $this->getFilledTree($category, $categories);
return $this->render($this->template, ['trees' => $trees, 'categories' => $categories]);
}
/**
* Find an entity by its id or return a 404 response
*
* @param string $id
*
* @return mixed
*
* @throws NotFoundHttpException
*/
protected function findEntityWithCategoriesOr404(string $id)
{
$product = $this->productRepository->find($id);
if (null === $product) {
throw new NotFoundHttpException(
sprintf('Product with with ID "%s" could not be found.', $id)
);
}
// With this version of the form we need to add missing values from family
// $this->valuesFiller->fillMissingValues($product);
// $this->productBuilder->addMissingAssociations($product);
return $product;
}
/**
* Fetch the filled tree
*
* @param CategoryInterface $parent
* @param Collection $categories
*
* @return CategoryInterface[]
*/
protected function getFilledTree($parent, Collection $categories): array
{
$categoryies = $this->categoryRepository->getFilledTree($parent, $categories);
foreach ($categoryies as $category) {
$category->setlocale($this->userContext->getCurrentLocaleCode());
}
return $this->categoryRepository->buildTreeNode($categoryies);
}
}
<?php
namespace Webkul\DamBundle\Controller;
/**
* @author Aman Srivastava (aman.srivastava462@webkul.com)
* @copyright 2019 Webkul Soft Pvt. Ltd.
*/
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Doctrine\ORM\EntityManagerInterface;
use Webkul\DamBundle\Entity\AssetMedia;
use Symfony\Component\HttpFoundation\JsonResponse;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
class MediaController extends Controller
{
/** @var FilesystemProvider */
protected $filesystemprovider;
/** @var FileRepository */
protected $fileRepo;
/**
* @param DamServices $damservices
* @param AssetRepository $assetrepository
* @param UserContext $usercontext
* @param FilesystemProvider $filesystemprovider
* @param Fil $fileStorer
*/
public function __construct(
$fileRepo,
$filesystemprovider
) {
$this->fileRepo = $fileRepo;
$this->filesystemprovider = $filesystemprovider;
}
/**
* @param string $identifier
*
* @throws NotFoundHttpException
*
* @return \StreamedFileResponse
*/
public function downloadAction($identifier)
{
$filename = urldecode($identifier);
if (strpos($filename, '/tmp/pim/file_storage/') !== false) {
$filename = str_replace('/tmp/pim/file_storage/', '', $filename);
}
$fs = $this->filesystemprovider->getFilesystem('catalogStorage');
if ($fs->has($filename)) {
$stream = $fs->readStream($filename);
$headers = [];
if (null !== $fileInfo = $this->fileRepo->findOneByIdentifier($filename)) {
$headers['Content-Disposition'] = sprintf(
'attachment; filename="%s"',
$fileInfo->getOriginalFilename()
);
}
return new \StreamedFileResponse($stream, 200, $headers);
}
throw new NotFoundHttpException(
sprintf('File with key "%s" could not be found.', $filename)
);
}
public function checkAzureAction()
{
$responseData['AzureBundle'] = false;
if (class_exists("Webkul\AzureBlobIntegrationBundle\AzureBlobIntegrationBundle")) {
$responseData['AzureBundle'] = true;
}
return new JsonResponse($responseData);
}
}
<?php
namespace Webkul\DamBundle\Controller;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* PostMedia Controller
*
* @author Aman Srivastav <aman.srivastava462@webkul.com>
* @copyright 2019 Webkul Soft Pvt. Ltd (https://webkul.com/)
*/
class PostMediaController
{
/** @var ValidatorInterface */
protected $validator;
/** @var PathGeneratorInterface */
protected $pathGenerator;
/** @var string */
protected $uploadDir;
/** @var FileStorer */
private $fileStorer;
/**
* @param ValidatorInterface $validator
* @param PathGeneratorInterface $pathGenerator
* @param string $uploadDir
*/
public function __construct(ValidatorInterface $validator, \PathGeneratorInterface $pathGenerator, $uploadDir, \FileStorer $fileStorer)
{
$this->validator = $validator;
$this->pathGenerator = $pathGenerator;
$this->uploadDir = $uploadDir;
$this->fileStorer = $fileStorer;
}
/**
* Post a new media and return it's temporary identifier
*
* @param Request $request
*
* @return Response
*/
public function postAction(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new RedirectResponse('/');
}
/** @var \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile */
$uploadedFile = $request->files->get('file');
$violations = $this->validator->validate($uploadedFile);
if (count($violations) > 0) {
$errors = [];
foreach ($violations as $violation) {
$errors[$violation->getPropertyPath()] = [
'message' => $violation->getMessage(),
'invalid_value' => $violation->getInvalidValue()
];
}
return new JsonResponse($errors, 400);
}
$file = $this->storeFile($uploadedFile);
return new JsonResponse(
[
'originalFilename' => $uploadedFile->getClientOriginalName(),
'filePath' => $file->getKey()
]
);
}
/**
* @param uploadedFile $uploadedFile
* @return fileData
*/
protected function storeFile(UploadedFile $uploadedFile)
{
return $this->fileStorer->store($uploadedFile, \FileStorage::CATALOG_STORAGE_ALIAS);
}
}
<?php
namespace Webkul\DamBundle\DBAL\Type;
use Doctrine\DBAL\Types\JsonArrayType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* Class JsonType
* @package CoreBundle\DBAL
*/
class JsonType extends JsonArrayType
{
/**
* @param array $fieldDeclaration
* @param AbstractPlatform $platform
* @return string
*/
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return 'json';
}
/**
* Convert the value of the field into a PHP data type
* @param mixed $value
* @param AbstractPlatform $platform
* @return array|mixed|null
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
return $value === null ? null : parent::convertToPHPValue($value, $platform);
}
/**
* Name of the db type
* @return string
*/
public function getName()
{
return 'json';
}
}
<?php
namespace Webkul\DamBundle\Datasource;
use Webkul\DamBundle\Repository\AssetRepository;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* Export Mapping datasource
*
* @author Webkul
* @copyright 2017 Webkul Software Pvt Ltd (http://www.webkul.com)
*/
class DamAssetDatasource extends \Datasource
{
/** @var AssetRepository */
protected $repository;
/** @var CustomObjectIdHydrator */
protected $hydrator;
/** @var array */
protected $parameters = [];
/**
* @param AssetRepository $om
* @param HydratorInterface $hydrator
*/
public function __construct(AssetRepository $repository, \HydratorInterface $hydrator)
{
$this->repository = $repository;
$this->hydrator = $hydrator;
}
/**
* @param string $method the query builder creation method
* @param array $config the query builder creation config
*
* @return Datasource
*/
protected function initializeQueryBuilder($method, array $config = [])
{
$this->qb = $this->repository->$method('wem');
$this->qb->leftJoin('wem.medias', 'md');
$this->qb->leftJoin('wem.tags', 'tg');
$this->qb->leftJoin('wem.category', 'category');
$this->qb->resetDQLPart('select');
$this->qb->addSelect('MIN(md.filePath) as thumbnail');
$this->qb->addSelect('wem.id, wem.code, wem.description, wem.starred, wem.createdAt, wem.updatedAt, wem.title, wem.alt');
$this->qb->groupBy('wem.id');
return $this;
}
/**
* {@inheritdoc}
*/
public function getResults()
{
return $this->hydrator->hydrate($this->qb);
}
}
<?php
namespace Webkul\DamBundle\Datasource\Orm;
use Oro\Bundle\DataGridBundle\Datasource\ResultRecord;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
class ResultRecordHydrator implements \HydratorInterface
{
/**
* {@inheritdoc}
*/
public function hydrate($qb, array $options = [])
{
$records = [];
foreach ($qb->getQuery()->execute() as $record) {
if ('array' === gettype($record) && isset($record[0])) {
$newRecord = $record[0];
if (count($record) > 1) {
foreach ($record as $key => $value) {
if (!is_numeric($key)) {
$newRecord->$key = $value;
}
}
}
$record = $newRecord;
if (array($record)) {
$record['is_checked'] = false;
}
} else {
if (array($record)) {
$record['is_checked'] = false;
}
}
$records[] = new ResultRecord($record);
}
return $records;
}
}
<?php
namespace Webkul\DamBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;
class CompatibilityCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$compatibilityClass = new \Webkul\DamBundle\Listener\ClassDefinationForCompatibility();
$compatibilityClass->createClassAliases();
}
}
<?php
namespace Webkul\DamBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Config\FileLocator;
class CompatibilityPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$file = fopen("test.txt", "w");
echo fwrite($file, "Hello World. Testing!" . rand(10, 100));
fclose($file);
if (!class_exists("\DataInvalidItem")) {
\class_alias("Akeneo\Component\Batch\Item\DataInvalidItem", "DataInvalidItem");
}
}
}
<?php
namespace Webkul\DamBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files.
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('webkuldam');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
<?php
namespace Webkul\DamBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration.
*
* @link http://symfony.com/doc/current/cookbook/bundles/extension.html
*/
class WebkulDamExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('event_listener.yml');
$loader->load('services.yml');
$loader->load('array_converters.yml');
$loader->load('attribute_types.yml');
$loader->load('comparators.yml');
$loader->load('updaters.yml');
$loader->load('providers.yml');
$loader->load('data_sources.yml');
$loader->load('repositories.yml');
$loader->load('jobs.yml');
$loader->load('steps.yml');
$loader->load('readers.yml');
$loader->load('writers.yml');
$loader->load('processors.yml');
$loader->load('job_parameters.yml');
$loader->load('form_entry.yml');
$loader->load('datagrid/asset_attribute.yml');
$loader->load('factories.yml');
$loader->load('serializers_standard.yml');
$loader->load('savers.yml');
$loader->load('controllers.yml');
$loader->load('context.yml');
$loader->load('remover.yml');
$loader->load('mass_actions.yml');
if (class_exists('Akeneo\Platform\CommunityVersion')) {
$versionClass = new \Akeneo\Platform\CommunityVersion();
} elseif (class_exists('Pim\Bundle\CatalogBundle\Version')) {
$versionClass = new \Pim\Bundle\CatalogBundle\Version();
}
$version = $versionClass::VERSION;
if ($version > '3.0') {
$versionDirectoryPrefix = '3.0/';
$loader->load('3.0/servicenames.yml');
// $loader->load('3.0/controllers.yml');
$loader->load('3.0/context.yml');
} else {
$loader->load('2.x/servicenames.yml');
}
if ($version > '4.0') {
$loader->load('4.0/factories.yml');
}
}
}
<?php
namespace Webkul\DamBundle\Entity;
/**
* Asset
*/
class Asset
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $code;
/**
* @var string
*/
private $description;
/**
* @var boolean
*/
private $starred = false;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var \DateTime
*/
private $updatedAt;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set code
*
* @param string $code
*
* @return Asset
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* @return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set description
*
* @param string $description
*
* @return Asset
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set starred
*
* @param boolean $starred
*
* @return Asset
*/
public function setStarred($starred)
{
$this->starred = $starred;
return $this;
}
/**
* Get starred
*
* @return boolean
*/
public function getStarred()
{
return $this->starred;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
*
* @return Asset
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* @param \DateTime $updatedAt
*
* @return Asset
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
public function setCreatedAtValue()
{
$this->createdAt = new \DateTime();
}
public function setUpdatedAtValue()
{
$this->updatedAt = new \DateTime();
}
/**
* @var string
*/
private $title;
/**
* @var string
*/
private $alt;
/**
* Set title
*
* @param string $title
*
* @return Asset
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set alt
*
* @param string $alt
*
* @return Asset
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* @return string
*/
public function getAlt()
{
return $this->alt;
}
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $medias;
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $tags;
/**
* Constructor
*/
public function __construct()
{
$this->medias = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add media
*
* @param \Webkul\DamBundle\Entity\AssetMedia $media
*
* @return Asset
*/
public function addMedia(\Webkul\DamBundle\Entity\AssetMedia $media)
{
$this->medias[] = $media;
return $this;
}
/**
* Remove media
*
* @param \Webkul\DamBundle\Entity\AssetMedia $media
*/
public function removeMedia(\Webkul\DamBundle\Entity\AssetMedia $media)
{
$this->medias->removeElement($media);
}
/**
* Get medias
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getMedias()
{
return $this->medias;
}
/**
* Add tag
*
* @param \Webkul\DamBundle\Entity\AssetTag $tag
*
* @return Asset
*/
public function addTag(\Webkul\DamBundle\Entity\AssetTag $tag)
{
$this->tags[] = $tag;
return $this;
}
/**
* Remove tag
*
* @param \Webkul\DamBundle\Entity\AssetTag $tag
*/
public function removeTag(\Webkul\DamBundle\Entity\AssetTag $tag)
{
$this->tags->removeElement($tag);
}
/**
* Get tags
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTags()
{
return $this->tags;
}
/**
* @var \Doctrine\Common\Collections\Collection
*/
public $category;
/**
* Add category
*
* @param \Webkul\DamBundle\Entity\AssetCategory $category
*
* @return Asset
*/
public function addCategory(\Webkul\DamBundle\Entity\AssetCategory $category)
{
$this->category[] = $category;
return $this;
}
/**
* Remove category
*
* @param \Webkul\DamBundle\Entity\AssetCategory $category
*/
public function removeCategory(\Webkul\DamBundle\Entity\AssetCategory $category)
{
$this->category->removeElement($category);
}
/**
* Get category
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCategory()
{
return $this->category;
}
/**
* @var \DateTime|null
*/
private $date;
/**
* Set date.
*
* @param \DateTime|null $date
*
* @return Asset
*/
public function setDate($date = null)
{
$this->date = $date;
return $this;
}
/**
* Get date.
*
* @return \DateTime|null
*/
public function getDate()
{
return $this->date;
}
/**
* @var \DateTime|null
*/
private $expiration_date;
/**
* Set expirationDate.
*
* @param \DateTime|null $expirationDate
*
* @return Asset
*/
public function setExpirationDate($expirationDate = null)
{
$this->expiration_date = $expirationDate;
return $this;
}
/**
* Get expirationDate.
*
* @return \DateTime|null
*/
public function getExpirationDate()
{
return $this->expiration_date;
}
/**
* @var string
*/
private $default_timezone;
/**
* Set defaultTimezone.
*
* @param string $defaultTimezone
*
* @return Asset
*/
public function setDefaultTimezone($defaultTimezone)
{
$this->default_timezone = $defaultTimezone;
return $this;
}
/**
* Get defaultTimezone.
*
* @return string
*/
public function getDefaultTimezone()
{
return $this->default_timezone;
}
}
<?php
namespace Webkul\DamBundle\Entity;
/**
* Asset
*/
class Asset
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $code;
/**
* @var string
*/
private $description;
/**
* @var boolean
*/
private $starred = false;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var \DateTime
*/
private $updatedAt;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set code
*
* @param string $code
*
* @return Asset
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* @return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set description
*
* @param string $description
*
* @return Asset
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set starred
*
* @param boolean $starred
*
* @return Asset
*/
public function setStarred($starred)
{
$this->starred = $starred;
return $this;
}
/**
* Get starred
*
* @return boolean
*/
public function getStarred()
{
return $this->starred;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
*
* @return Asset
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* @param \DateTime $updatedAt
*
* @return Asset
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
public function setCreatedAtValue()
{
$this->createdAt = new \DateTime();
}
public function setUpdatedAtValue()
{
$this->updatedAt = new \DateTime();
}
/**
* @var string
*/
private $title;
/**
* @var string
*/
private $alt;
/**
* Set title
*
* @param string $title
*
* @return Asset
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set alt
*
* @param string $alt
*
* @return Asset
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* @return string
*/
public function getAlt()
{
return $this->alt;
}
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $medias;
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $tags;
/**
* Constructor
*/
public function __construct()
{
$this->medias = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add media
*
* @param \Webkul\DamBundle\Entity\AssetMedia $media
*
* @return Asset
*/
public function addMedia(\Webkul\DamBundle\Entity\AssetMedia $media)
{
$this->medias[] = $media;
return $this;
}
/**
* Remove media
*
* @param \Webkul\DamBundle\Entity\AssetMedia $media
*/
public function removeMedia(\Webkul\DamBundle\Entity\AssetMedia $media)
{
$this->medias->removeElement($media);
}
/**
* Get medias
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getMedias()
{
return $this->medias;
}
/**
* Add tag
*
* @param \Webkul\DamBundle\Entity\AssetTag $tag
*
* @return Asset
*/
public function addTag(\Webkul\DamBundle\Entity\AssetTag $tag)
{
$this->tags[] = $tag;
return $this;
}
/**
* Remove tag
*
* @param \Webkul\DamBundle\Entity\AssetTag $tag
*/
public function removeTag(\Webkul\DamBundle\Entity\AssetTag $tag)
{
$this->tags->removeElement($tag);
}
/**
* Get tags
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTags()
{
return $this->tags;
}
}
<?php
namespace Webkul\DamBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;
$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
* AssetCategory
*/
class AssetCategory extends \BaseCategory implements \CategoryInterface
{
/**
* @var integer
*/
protected $id;
/**
* @var string
*/
protected $code;
/**
* @var \DateTime
*/
protected $created;
/**
* @var integer
*/
protected $root;
/**
* @var integer
*/
protected $level;
/**
* @var integer
*/
protected $left;
/**
* @var integer
*/
protected $right;
/**
* @var \Doctrine\Common\Collections\Collection
*/
protected $translations;
/**
* @var \Doctrine\Common\Collections\Collection
*/
protected $children;
/**
* @var CategoryInterface
*/
protected $parent;
/**
* Used locale to override Translation listener's locale
* this is not a mapped field of entity metadata, just a simple property
*
* @var string
*/
protected $locale;
/**
* Constructor
*/
public function __construct()
{
$this->translations = new \Doctrine\Common\Collections\ArrayCollection();
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set code
*
* @param string $code
*
* @return AssetCategory
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* @return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set created
*
* @param \DateTime $created
*
* @return AssetCategory
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set root
*
* @param integer $root
*
* @return AssetCategory
*/
public function setRoot($root)
{
$this->root = $root;
return $this;
}
/**
* Get root
*
* @return integer
*/
public function getRoot()
{
return $this->root;
}
/**
* Set level
*
* @param integer $level
*
* @return AssetCategory
*/
public function setLevel($level)
{
$this->level = $level;
return $this;
}
/**
* Get level
*
* @return integer
*/
public function getLevel()
{
return $this->level;
}
/**
* Set left
*
* @param integer $left
*
* @return AssetCategory
*/
public function setLeft($left)
{
$this->left = $left;
return $this;
}
/**
* Get left
*
* @return integer
*/
public function getLeft()
{
return $this->left;
}
/**
* Set right
*
* @param integer $right
*
* @return AssetCategory
*/
public function setRight($right)
{
$this->right = $right;
return $this;
}
/**
* Get right
*
* @return integer
*/
public function getRight()
{
return $this->right;
}
/**
* Remove translation
*
* @param \Webkul\DamBundle\Model\AssetCategoryTranslationInterface $translation
*/
public function removeTranslation(\Webkul\DamBundle\Model\AssetCategoryTranslationInterface $translation)
{
$this->translations->removeElement($translation);
}
/**
* Remove translation
*
*/
public function removeTranslations()
{
$this->translations = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get translations
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTranslations()
{
// if()
return $this->translations;
}
/**
* Add child
*
* @param CategoryInterface $child
*
* @return AssetCategory
*/
public function addChild(\CategoryInterface $child)
{
$this->children[] = $child;
return $this;
}
/**
* Remove child
*
* @param CategoryInterface $child
*/
public function removeChild(\CategoryInterface $child)
{
$this->children->removeElement($child);
}
/**
* Get children
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* Set parent
*
* @param CategoryInterface $parent
*
* @return AssetCategory
*/
public function setParent(\CategoryInterface $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* @return CategoryInterface
*/
public function getParent()
{
return $this->parent;
}
public function setLocale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* {@inheritdoc}
*/
public function getTranslation($locale = null)
{
$locale = ($locale) ? $locale : $this->locale;
if (null === $locale) {
return null;
}
foreach ($this->getTranslations() as $translation) {
if ($translation->getLocale() == $locale) {
return $translation;
}
}
$translationClass = $this->getTranslationFQCN();
$translation = new $translationClass();
$translation->setLocale($locale);
$translation->setForeignKey($this);
$this->addTranslation($translation);
return $translation;
}
public function addTranslation($translation)
{
if (!$this->translations->contains($translation)) {
$this->translations->add($translation);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function getTranslationFQCN()
{
return 'Webkul\DamBundle\Entity\AssetCategoryTranslation';
}
/**
* Get label
*
* @return string
*/
public function getLabel()
{
$translated = ($this->getTranslation()) ? $this->getTranslation()->getLabel() : null;
return ($translated !== '' && $translated !== null) ? $translated : '['.$this->getCode().']';
}
/**
* Set label
*
* @param string $label
*
* @return CategoryInterface
*/
public function setLabel($label)
{
$this->getTranslation()->setLabel($label);
return $this;
}
/**
* Returns the channels linked to the category
*
* @return ArrayCollection
*/
public function getChannels()
{
return $this->channels;
}
/**
* @return string
*/
public function __toString()
{
return $this->getLabel();
}
/**
* {@inheritdoc}
*/
public function getReference()
{
return $this->code;
}
/**
* {@inheritdoc}
*/
public function hasChildren()
{
return count($this->getChildren()) > 0;
}
/**
* {@inheritdoc}
*/
public function isRoot()
{
return (null === $this->getParent());
}
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $asset;
/**
* Add asset
*
* @param \Webkul\DamBundle\Entity\Asset $asset
*
* @return AssetCategory
*/
public function addAsset(\Webkul\DamBundle\Entity\Asset $asset)
{
$this->asset[] = $asset;
return $this;
}
/**
* Remove asset
*
* @param \Webkul\DamBundle\Entity\Asset $asset
*/
public function removeAsset(\Webkul\DamBundle\Entity\Asset $asset)
{
$this->asset->removeElement($asset);
}
/**
* Get asset
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getAsset()
{
return $this->asset;
}
}
<?php
namespace Webkul\DamBundle\Entity;
use Akeneo\Component\Classification\Model\CategoryInterface;
use Akeneo\Component\Localization\Model\TranslationInterface;
use Akeneo\Component\Classification\Model\Category as BaseCategory;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* AssetCategory
*/
class AssetCategory extends BaseCategory implements CategoryInterface
{
/**
* @var integer
*/
protected $id;
/**
* @var string
*/
protected $code;
/**
* @var \DateTime
*/
protected $created;
/**
* @var integer
*/
protected $root;
/**
* @var integer
*/
protected $level;
/**
* @var integer
*/
protected $left;
/**
* @var integer
*/
protected $right;
/**
* @var \Doctrine\Common\Collections\Collection
*/
protected $translations;
/**
* @var \Doctrine\Common\Collections\Collection
*/
protected $children;
/**
* @var CategoryInterface
*/
protected $parent;
/**
* Used locale to override Translation listener's locale
* this is not a mapped field of entity metadata, just a simple property
*
* @var string
*/
protected $locale;
/**
* Constructor
*/
public function __construct()
{
$this->translations = new \Doctrine\Common\Collections\ArrayCollection();
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set code
*
* @param string $code
*
* @return AssetCategory
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* @return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set created
*
* @param \DateTime $created
*
* @return AssetCategory
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set root
*
* @param integer $root
*
* @return AssetCategory
*/
public function setRoot($root)
{
$this->root = $root;
return $this;
}
/**
* Get root
*
* @return integer
*/
public function getRoot()
{
return $this->root;
}
/**
* Set level
*
* @param integer $level
*
* @return AssetCategory
*/
public function setLevel($level)
{
$this->level = $level;
return $this;
}
/**
* Get level
*
* @return integer
*/
public function getLevel()
{
return $this->level;
}
/**
* Set left
*
* @param integer $left
*
* @return AssetCategory
*/
public function setLeft($left)
{
$this->left = $left;
return $this;
}
/**
* Get left
*
* @return integer
*/
public function getLeft()
{
return $this->left;
}
/**
* Set right
*
* @param integer $right
*
* @return AssetCategory
*/
public function setRight($right)
{
$this->right = $right;
return $this;
}
/**
* Get right
*
* @return integer
*/
public function getRight()
{
return $this->right;
}
/**
* Remove translation
*
* @param \Webkul\DamBundle\Model\AssetCategoryTranslationInterface $translation
*/
public function removeTranslation(\Webkul\DamBundle\Model\AssetCategoryTranslationInterface $translation)
{
$this->translations->removeElement($translation);
}
/**
* Remove translation
*
*/
public function removeTranslations()
{
$this->translations = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get translations
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTranslations()
{
// if()
return $this->translations;
}
/**
* Add child
*
* @param CategoryInterface $child
*
* @return AssetCategory
*/
public function addChild(CategoryInterface $child)
{
$this->children[] = $child;
return $this;
}
/**
* Remove child
*
* @param CategoryInterface $child
*/
public function removeChild(CategoryInterface $child)
{
$this->children->removeElement($child);
}
/**
* Get children
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* Set parent
*
* @param CategoryInterface $parent
*
* @return AssetCategory
*/
public function setParent(CategoryInterface $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* @return CategoryInterface
*/
public function getParent()
{
return $this->parent;
}
public function setLocale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* {@inheritdoc}
*/
public function getTranslation($locale = null)
{
$locale = ($locale) ? $locale : $this->locale;
if (null === $locale) {
return null;
}
foreach ($this->getTranslations() as $translation) {
if ($translation->getLocale() == $locale) {
return $translation;
}
}
$translationClass = $this->getTranslationFQCN();
$translation = new $translationClass();
$translation->setLocale($locale);
$translation->setForeignKey($this);
$this->addTranslation($translation);
return $translation;
}
public function addTranslation($translation)
{
if (!$this->translations->contains($translation)) {
$this->translations->add($translation);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function getTranslationFQCN()
{
return 'Webkul\DamBundle\Entity\AssetCategoryTranslation';
}
/**
* Get label
*
* @return string
*/
public function getLabel()
{
$translated = ($this->getTranslation()) ? $this->getTranslation()->getLabel() : null;
return ($translated !== '' && $translated !== null) ? $translated : '['.$this->getCode().']';
}
/**
* Set label
*
* @param string $label
*
* @return CategoryInterface
*/
public function setLabel($label)
{
$this->getTranslation()->setLabel($label);
return $this;
}
/**
* Returns the channels linked to the category
*
* @return ArrayCollection
*/
public function getChannels()
{
return $this->channels;
}
/**
* @return string
*/
public function __toString()
{
return $this->getLabel();
}
/**
* {@inheritdoc}
*/
public function getReference()
{
return $this->code;
}
/**
* {@inheritdoc}
*/
public function hasChildren()
{
return count($this->getChildren()) > 0;
}
/**
* {@inheritdoc}
*/
public function isRoot()
{
return (null === $this->getParent());
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment