1
0
mirror of https://github.com/ToxicCrack/PrintABrick.git synced 2025-05-29 18:20:18 -07:00

Fix coding style

This commit is contained in:
David Hübner 2017-04-28 16:17:49 +02:00
parent 4d81d527fc
commit ff408f1795
28 changed files with 172 additions and 224 deletions

View File

@ -113,7 +113,7 @@ class Brickset extends \SoapClient
$response = $this->call('getSets', $parameters)->sets; $response = $this->call('getSets', $parameters)->sets;
return is_array($response) ? $response : [$this->getSet($response->getSetID())]; return is_array($response) ? $response : [$response];
} }
/** /**

View File

@ -29,9 +29,8 @@ class BricksetManager
public function getThemes() public function getThemes()
{ {
if(!$data = unserialize($this->cache->fetch('themes'))) if (!$data = unserialize($this->cache->fetch('themes'))) {
{ $data = $this->bricksetClient->getThemes();
$data = $this->bricksetClient->getThemes();
$this->cache->save('themes', serialize($data), self::CACHE_LIFETIME); $this->cache->save('themes', serialize($data), self::CACHE_LIFETIME);
} }
@ -40,11 +39,10 @@ class BricksetManager
public function getSubthemesByTheme($theme) public function getSubthemesByTheme($theme)
{ {
$key = "subthemes-".$theme; $key = 'subthemes-'.$theme;
if(!$data = unserialize($this->cache->fetch($key))) if (!$data = unserialize($this->cache->fetch($key))) {
{ $data = $this->bricksetClient->getSubthemes($theme);
$data = $this->bricksetClient->getSubthemes($theme);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME); $this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
} }
@ -53,11 +51,10 @@ class BricksetManager
public function getYearsByTheme($theme) public function getYearsByTheme($theme)
{ {
$key = "years-".$theme; $key = 'years-'.$theme;
if(!$data = unserialize($this->cache->fetch($key))) if (!$data = unserialize($this->cache->fetch($key))) {
{ $data = $this->bricksetClient->getYears($theme);
$data = $this->bricksetClient->getYears($theme);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME); $this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
} }
@ -66,9 +63,9 @@ class BricksetManager
public function getSetById($id) public function getSetById($id)
{ {
$key = "set-".$id; $key = 'set-'.$id;
if(!$data = unserialize($this->cache->fetch($key))) { if (!$data = unserialize($this->cache->fetch($key))) {
$data = $this->bricksetClient->getSet($id); $data = $this->bricksetClient->getSet($id);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME); $this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
} }
@ -78,10 +75,9 @@ class BricksetManager
public function getSetByNumber($number) public function getSetByNumber($number)
{ {
$key = "set-".$number; $key = 'set-'.$number;
if(!$data = unserialize($this->cache->fetch($key))) if (!$data = unserialize($this->cache->fetch($key))) {
{
$sets = $this->bricksetClient->getSets(['setNumber' => $number]); $sets = $this->bricksetClient->getSets(['setNumber' => $number]);
$data = isset($sets[0]) ? $sets[0] : null; $data = isset($sets[0]) ? $sets[0] : null;
@ -93,10 +89,9 @@ class BricksetManager
public function getSetInstructions($id) public function getSetInstructions($id)
{ {
$key = "instructions-".$id; $key = 'instructions-'.$id;
if(!$data = unserialize($this->cache->fetch($key))) if (!$data = unserialize($this->cache->fetch($key))) {
{
$data = $this->bricksetClient->getInstructions($id); $data = $this->bricksetClient->getInstructions($id);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME); $this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
} }
@ -106,10 +101,9 @@ class BricksetManager
public function getSetReviews($id) public function getSetReviews($id)
{ {
$key = "reviews-".$id; $key = 'reviews-'.$id;
if(!$data = unserialize($this->cache->fetch($key))) if (!$data = unserialize($this->cache->fetch($key))) {
{
$data = $this->bricksetClient->getReviews($id); $data = $this->bricksetClient->getReviews($id);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME); $this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
} }
@ -119,11 +113,10 @@ class BricksetManager
public function getAdditionalImages($id) public function getAdditionalImages($id)
{ {
$key = "images-".$id; $key = 'images-'.$id;
if(!$data = unserialize($this->cache->fetch($key))) if (!$data = unserialize($this->cache->fetch($key))) {
{ $data = $this->bricksetClient->getAdditionalImages($id);
$data = $this->bricksetClient->getAdditionalImages($id);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME); $this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
} }

View File

@ -157,25 +157,27 @@ class RebrickableManager
return $this->serializer->denormalize($data, Set::class.'[]', self::FORMAT); return $this->serializer->denormalize($data, Set::class.'[]', self::FORMAT);
} }
// /** /**
// * Get a list of all parts (normal + spare) used in a set. * Get a list of all parts (normal + spare) used in a set.
// * *
// * @param $setId * @param $setId
// * @param $page * @param $page
// * *
// * @return * @return
// */ */
// public function getSetParts($setId, $page = null) public function getSetParts($setId, $page = null)
// { {
// $options = [ $options = [
// 'query' => [ 'query' => [
// 'page' => $page, 'page' => $page,
// ], ],
// ]; ];
//
// $response = $this->rebrickableClient->call('GET', 'lego/sets/'.$setId.'/parts', $options); $response = $this->rebrickableClient->call('GET', 'lego/sets/'.$setId.'/parts', $options);
// $data = json_decode($response, true)['results']; $data = json_decode($response, true)['results'];
//
// return $this->serializer->denormalize($data, Part::class.'[]', self::FORMAT); dump($data);
// }
return $this->serializer->denormalize($data, Part::class.'[]', self::FORMAT);
}
} }

View File

@ -31,37 +31,38 @@ class InitDataCommand extends ContainerAwareCommand
$returnCode = $loadModelsCommand->run(new ArrayInput([ $returnCode = $loadModelsCommand->run(new ArrayInput([
'command' => 'app:load:models', 'command' => 'app:load:models',
'ldraw' => $input->getArgument('ldraw'), 'ldraw' => $input->getArgument('ldraw'),
'--all' => true '--all' => true,
]),$output); ]), $output);
if($returnCode) { if ($returnCode) {
return 1; return 1;
} }
$loadRebrickableCommad = $this->getApplication()->find('app:load:rebrickable'); $loadRebrickableCommad = $this->getApplication()->find('app:load:rebrickable');
$returnCode = $loadRebrickableCommad->run(new ArrayInput([ $returnCode = $loadRebrickableCommad->run(new ArrayInput([
'command' => 'app:load:rebrickable']),$output); 'command' => 'app:load:rebrickable', ]), $output);
if($returnCode) { if ($returnCode) {
return 1; return 1;
} }
$loadRelationsCommand = $this->getApplication()->find('app:load:relations'); $loadRelationsCommand = $this->getApplication()->find('app:load:relations');
$returnCode = $loadRelationsCommand->run(new ArrayInput([ $returnCode = $loadRelationsCommand->run(new ArrayInput([
'command' => 'app:load:relations']),$output); 'command' => 'app:load:relations', ]), $output);
if($returnCode) { if ($returnCode) {
return 1; return 1;
} }
$loadImagesCommand = $this->getApplication()->find('app:load:images'); $loadImagesCommand = $this->getApplication()->find('app:load:images');
$returnCode = $loadImagesCommand->run(new ArrayInput([ $returnCode = $loadImagesCommand->run(new ArrayInput([
'command' => 'app:load:images', 'command' => 'app:load:images',
'--color' => -1, '--color' => -1,
'--rebrickable' => true, '--rebrickable' => true,
'--models' => true '--models' => true,
]),$output); ]), $output);
return 0;
} }
} }

View File

@ -2,10 +2,7 @@
namespace AppBundle\Command; namespace AppBundle\Command;
use AppBundle\Utils\RenderSTL;
use Libre3d\Render3d\Render3d;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputOption;
@ -37,11 +34,11 @@ class LoadModelImagesCommand extends ContainerAwareCommand
$color = $input->getOption('color'); $color = $input->getOption('color');
$url = $input->getOption('url'); $url = $input->getOption('url');
if($color !== null && $input->getOption('rebrickable')) { if ($color !== null && $input->getOption('rebrickable')) {
$imageLoaderService->loadColorFromRebrickable($color, $url); $imageLoaderService->loadColorFromRebrickable($color, $url);
} }
if($input->getOption('models')) { if ($input->getOption('models')) {
$imageLoaderService->loadMissingModelImages(); $imageLoaderService->loadMissingModelImages();
} }
} }

View File

@ -34,6 +34,7 @@ class LoadModelsCommand extends ContainerAwareCommand
{ {
if (!$this->lock()) { if (!$this->lock()) {
$output->writeln('The command is already running in another process.'); $output->writeln('The command is already running in another process.');
return 1; return 1;
} }
@ -43,8 +44,9 @@ class LoadModelsCommand extends ContainerAwareCommand
$ldraw = $input->getArgument('ldraw'); $ldraw = $input->getArgument('ldraw');
if(!$input->getOption('file') && !$input->getOption('all')){ if (!$input->getOption('file') && !$input->getOption('all')) {
$output->writeln('Either the --all or --file option is required'); $output->writeln('Either the --all or --file option is required');
return 1; return 1;
} }
@ -86,6 +88,7 @@ class LoadModelsCommand extends ContainerAwareCommand
} else { } else {
$output->writeln("<error>{$ldraw} is not a valid path!</error>"); $output->writeln("<error>{$ldraw} is not a valid path!</error>");
$this->release(); $this->release();
return 1; return 1;
} }

View File

@ -26,6 +26,7 @@ class LoadRebrickableDataCommand extends ContainerAwareCommand
$rebrickableLoader->loadAll(); $rebrickableLoader->loadAll();
} catch (Exception $exception) { } catch (Exception $exception) {
$output->writeln("<error>{$exception->getMessage()}</error>"); $output->writeln("<error>{$exception->getMessage()}</error>");
return 1; return 1;
} }
} }

View File

@ -21,10 +21,9 @@ class LoadRelationCommand extends ContainerAwareCommand
$relationLoader = $this->getContainer()->get('service.loader.relation'); $relationLoader = $this->getContainer()->get('service.loader.relation');
$relationLoader->setOutput($output); $relationLoader->setOutput($output);
$output->writeln([ $output->writeln([
'<fg=cyan>------------------------------------------------------------------------------</>', '<fg=cyan>------------------------------------------------------------------------------</>',
"<fg=cyan>Loading relations between parts and models...</>", '<fg=cyan>Loading relations between parts and models...</>',
'<fg=cyan>------------------------------------------------------------------------------</>', '<fg=cyan>------------------------------------------------------------------------------</>',
]); ]);

View File

@ -19,7 +19,7 @@ class MediaController extends Controller
* *
* @return Response * @return Response
*/ */
public function stlAction($path) public function fileAction($path)
{ {
$mediaFilesystem = $this->get('oneup_flysystem.media_filesystem'); $mediaFilesystem = $this->get('oneup_flysystem.media_filesystem');

View File

@ -3,13 +3,10 @@
namespace AppBundle\Controller\Rebrickable; namespace AppBundle\Controller\Rebrickable;
use AppBundle\Api\Exception\EmptyResponseException; use AppBundle\Api\Exception\EmptyResponseException;
use AppBundle\Entity\Rebrickable\Category;
use AppBundle\Entity\Rebrickable\Part; use AppBundle\Entity\Rebrickable\Part;
use AppBundle\Entity\Rebrickable\Set; use AppBundle\Entity\Rebrickable\Set;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
/** /**
* Part controller. * Part controller.
@ -22,7 +19,6 @@ class PartController extends Controller
* Finds and displays a part entity. * Finds and displays a part entity.
* *
* @Route("/{number}", name="reb_part_detail") * @Route("/{number}", name="reb_part_detail")
* @Method("GET")
*/ */
public function detailAction(Part $part) public function detailAction(Part $part)
{ {

View File

@ -39,25 +39,25 @@ class SearchController extends Controller
{ {
$query = trim(strip_tags($request->get('query'))); $query = trim(strip_tags($request->get('query')));
$modelsResult = $this->get('repository.ldraw.model')->findByQuery($query,7); $modelsResult = $this->get('repository.ldraw.model')->findByQuery($query, 7);
$models = []; $models = [];
/** @var Model $model */ /** @var Model $model */
foreach ($modelsResult as $model) { foreach ($modelsResult as $model) {
$models[] = [ $models[] = [
'title' => $model->getNumber().' '.$model->getName(), 'title' => $model->getNumber().' '.$model->getName(),
'url' => $this->generateUrl('model_detail',['number' => $model->getNumber()]), 'url' => $this->generateUrl('model_detail', ['number' => $model->getNumber()]),
]; ];
} }
$setsResult = $this->get('repository.rebrickable.set')->findByQuery($query,7); $setsResult = $this->get('repository.rebrickable.set')->findByQuery($query, 7);
$sets = []; $sets = [];
/** @var Set $set */ /** @var Set $set */
foreach ($setsResult as $set) { foreach ($setsResult as $set) {
$sets[] = [ $sets[] = [
'title' => $set->getNumber().' '.$set->getName(), 'title' => $set->getNumber().' '.$set->getName(),
'url' => $this->generateUrl('set_detail',['number' => $set->getNumber()]), 'url' => $this->generateUrl('set_detail', ['number' => $set->getNumber()]),
]; ];
} }
@ -71,11 +71,10 @@ class SearchController extends Controller
'category1' => [ 'category1' => [
'name' => 'Models', 'name' => 'Models',
'results' => $models, 'results' => $models,
] ],
] ],
]); ]);
return $response; return $response;
} }
} }

View File

@ -8,7 +8,7 @@ class ErrorParsingLineException extends FileException
{ {
public function __construct($path, $line, $message = '', $code = 0, Throwable $previous = null) public function __construct($path, $line, $message = '', $code = 0, Throwable $previous = null)
{ {
$message = sprintf('Error parsing line \""%s"\" "%s" file.',$line, $path); $message = sprintf('Error parsing line \""%s"\" "%s" file.', $line, $path);
parent::__construct($path, $message, $code, $previous); parent::__construct($path, $message, $code, $previous);
} }

View File

@ -34,7 +34,6 @@ class SetFilterType extends AbstractType
}); });
}, },
]); ]);
} }
public function getBlockPrefix() public function getBlockPrefix()

View File

@ -19,7 +19,7 @@ class ModelRepository extends BaseRepository
{ {
$queryBuilder = $this->createQueryBuilder('model') $queryBuilder = $this->createQueryBuilder('model')
->where('model.name NOT LIKE :obsolete') ->where('model.name NOT LIKE :obsolete')
->setParameter('obsolete','~%'); ->setParameter('obsolete', '~%');
return $queryBuilder; return $queryBuilder;
} }
@ -70,7 +70,7 @@ class ModelRepository extends BaseRepository
->addSelect('inventory_part') ->addSelect('inventory_part')
->distinct(true); ->distinct(true);
return ($queryBuilder->getQuery()->getScalarResult()); return $queryBuilder->getQuery()->getScalarResult();
} }
public function findAllBySetNumber($number) public function findAllBySetNumber($number)
@ -106,10 +106,10 @@ class ModelRepository extends BaseRepository
return $queryBuilder->getQuery()->getResult(); return $queryBuilder->getQuery()->getResult();
} }
public function findByQuery($query, $limit = null) { public function findByQuery($query, $limit = null)
{
$queryBuilder = $this->createQueryBuilder('model'); $queryBuilder = $this->createQueryBuilder('model');
$queryBuilder->where( $queryBuilder->where(
$queryBuilder->expr()->orX( $queryBuilder->expr()->orX(
$queryBuilder->expr()->like('model.number', ':number'), $queryBuilder->expr()->like('model.number', ':number'),
@ -118,7 +118,7 @@ class ModelRepository extends BaseRepository
->setParameter('name', '%'.$query.'%') ->setParameter('name', '%'.$query.'%')
->setParameter('number', $query.'%'); ->setParameter('number', $query.'%');
if($limit) { if ($limit) {
$queryBuilder->setMaxResults($limit); $queryBuilder->setMaxResults($limit);
} }

View File

@ -28,7 +28,7 @@ class SubpartRepository extends BaseRepository
$subpart = new Subpart(); $subpart = new Subpart();
$colorRepository = $this->getEntityManager()->getRepository(Color::class); $colorRepository = $this->getEntityManager()->getRepository(Color::class);
if(!($color = $colorRepository->find($colorId))) { if (!($color = $colorRepository->find($colorId))) {
$color = $colorRepository->find(-1); $color = $colorRepository->find(-1);
} }

View File

@ -4,7 +4,6 @@ namespace AppBundle\Repository\Rebrickable;
use AppBundle\Entity\Rebrickable\Set; use AppBundle\Entity\Rebrickable\Set;
use AppBundle\Repository\BaseRepository; use AppBundle\Repository\BaseRepository;
use Doctrine\ORM\Query;
class InventoryRepository extends BaseRepository class InventoryRepository extends BaseRepository
{ {

View File

@ -2,7 +2,6 @@
namespace AppBundle\Repository\Rebrickable; namespace AppBundle\Repository\Rebrickable;
use AppBundle\Entity\LDraw\Category;
use AppBundle\Entity\LDraw\Model; use AppBundle\Entity\LDraw\Model;
use AppBundle\Entity\Rebrickable\Inventory; use AppBundle\Entity\Rebrickable\Inventory;
use AppBundle\Entity\Rebrickable\Inventory_Part; use AppBundle\Entity\Rebrickable\Inventory_Part;
@ -16,8 +15,9 @@ class Inventory_PartRepository extends BaseRepository
* Finds all inventoty_parts in newest inventory of set. * Finds all inventoty_parts in newest inventory of set.
* *
* @param string $number Unique number identifier of set * @param string $number Unique number identifier of set
* @param bool $spare If true - find all spare parts, false - find all regular parts, null - spare and regular parts * @param bool $spare If true - find all spare parts, false - find all regular parts, null - spare and regular parts
* @param bool $model If true - find all parts with model relation, false - find all parts without model relation, null - all parts * @param bool $model If true - find all parts with model relation, false - find all parts without model relation, null - all parts
*
* @return array * @return array
*/ */
public function findAllBySetNumber($number, $spare = null, $model = null) public function findAllBySetNumber($number, $spare = null, $model = null)
@ -28,17 +28,16 @@ class Inventory_PartRepository extends BaseRepository
->where('inventory_part.inventory = :inventory') ->where('inventory_part.inventory = :inventory')
->setParameter('inventory', $inventory); ->setParameter('inventory', $inventory);
if ($spare !== null) {
if($spare !== null) {
$queryBuilder $queryBuilder
->andWhere('inventory_part.spare = :spare') ->andWhere('inventory_part.spare = :spare')
->setParameter('spare', $spare); ->setParameter('spare', $spare);
} }
if($model !== null) { if ($model !== null) {
$queryBuilder $queryBuilder
->join(Part::class, 'part', JOIN::WITH, 'inventory_part.part = part'); ->join(Part::class, 'part', JOIN::WITH, 'inventory_part.part = part');
if($model === true) { if ($model === true) {
$queryBuilder->andWhere('part.model IS NOT NULL'); $queryBuilder->andWhere('part.model IS NOT NULL');
} else { } else {
$queryBuilder->andWhere('part.model IS NULL'); $queryBuilder->andWhere('part.model IS NULL');

View File

@ -6,7 +6,6 @@ use AppBundle\Entity\LDraw\Model;
use AppBundle\Entity\Rebrickable\Category; use AppBundle\Entity\Rebrickable\Category;
use AppBundle\Entity\Rebrickable\Inventory; use AppBundle\Entity\Rebrickable\Inventory;
use AppBundle\Entity\Rebrickable\Inventory_Part; use AppBundle\Entity\Rebrickable\Inventory_Part;
use AppBundle\Entity\Rebrickable\Set;
use AppBundle\Repository\BaseRepository; use AppBundle\Repository\BaseRepository;
use Doctrine\ORM\Query\Expr\Join; use Doctrine\ORM\Query\Expr\Join;

View File

@ -49,14 +49,15 @@ class SetRepository extends BaseRepository
return $queryBuilder->getQuery()->getResult(); return $queryBuilder->getQuery()->getResult();
} }
public function findByQuery($query, $limit = null) { public function findByQuery($query, $limit = null)
{
$queryBuilder = $this->createQueryBuilder('s') $queryBuilder = $this->createQueryBuilder('s')
->where('s.name LIKE :name') ->where('s.name LIKE :name')
->orWhere('s.number LIKE :number') ->orWhere('s.number LIKE :number')
->setParameter('name', '%'.$query.'%') ->setParameter('name', '%'.$query.'%')
->setParameter('number', $query.'%'); ->setParameter('number', $query.'%');
if($limit) { if ($limit) {
$queryBuilder->setMaxResults($limit); $queryBuilder->setMaxResults($limit);
} }

View File

@ -69,8 +69,8 @@ abstract class BaseLoader
protected function initProgressBar($total, $format = 'loader') protected function initProgressBar($total, $format = 'loader')
{ {
$this->progressBar = new ProgressBar($this->output, $total); $this->progressBar = new ProgressBar($this->output, $total);
ProgressBar::setFormatDefinition('loader', '[%current% / %max%] [%bar%] %percent:3s%% (%elapsed:6s%/%estimated:-6s%) (%message%)' . PHP_EOL); ProgressBar::setFormatDefinition('loader', '[%current% / %max%] [%bar%] %percent:3s%% (%elapsed:6s%/%estimated:-6s%) (%message%)'.PHP_EOL);
ProgressBar::setFormatDefinition('download', '[%progress% / %size%] [%bar%] %percent:3s%% (%elapsed:6s%/%estimated:-6s%)' . PHP_EOL); ProgressBar::setFormatDefinition('download', '[%progress% / %size%] [%bar%] %percent:3s%% (%elapsed:6s%/%estimated:-6s%)'.PHP_EOL);
$this->progressBar->setFormat($format); $this->progressBar->setFormat($format);
$this->progressBar->setBarWidth(70); $this->progressBar->setBarWidth(70);
@ -83,12 +83,12 @@ abstract class BaseLoader
case STREAM_NOTIFY_FILE_SIZE_IS: case STREAM_NOTIFY_FILE_SIZE_IS:
$this->initProgressBar($bytes_max); $this->initProgressBar($bytes_max);
$this->progressBar->setFormat('download'); $this->progressBar->setFormat('download');
$this->progressBar->setMessage($this->formatTransformer->bytesToSize($bytes_max),'size'); $this->progressBar->setMessage($this->formatTransformer->bytesToSize($bytes_max), 'size');
$this->progressBar->setRedrawFrequency(1024*1024); $this->progressBar->setRedrawFrequency(1024 * 1024);
break; break;
case STREAM_NOTIFY_PROGRESS: case STREAM_NOTIFY_PROGRESS:
$this->progressBar->setProgress($bytes_transferred); $this->progressBar->setProgress($bytes_transferred);
$this->progressBar->setMessage($this->formatTransformer->bytesToSize($bytes_transferred),'progress'); $this->progressBar->setMessage($this->formatTransformer->bytesToSize($bytes_transferred), 'progress');
break; break;
case STREAM_NOTIFY_COMPLETED: case STREAM_NOTIFY_COMPLETED:
$this->progressBar->finish(); $this->progressBar->finish();
@ -128,8 +128,10 @@ abstract class BaseLoader
return $temp; return $temp;
} }
protected function writeOutput(array $lines) { protected function writeOutput(array $lines)
if($this->output) {
if ($this->output) {
$this->output->writeln($lines); $this->output->writeln($lines);
}
} }
} }

View File

@ -30,16 +30,16 @@ class ImageLoader extends BaseLoader
*/ */
public function loadColorFromRebrickable($color, $path = null) public function loadColorFromRebrickable($color, $path = null)
{ {
if(!$path) { if (!$path) {
$path = $this->rebrickableDownloadUrl."ldraw/parts_{$color}.zip"; $path = $this->rebrickableDownloadUrl."ldraw/parts_{$color}.zip";
} }
$file = $this->downloadFile($path); $file = $this->downloadFile($path);
$zip = new \ZipArchive($file); $zip = new \ZipArchive($file);
if ($zip->open($file) === TRUE) { if ($zip->open($file) === true) {
$this->output->writeln([ $this->output->writeln([
"Extracting ZIP file into {$this->mediaFilesystem->getAdapter()->getPathPrefix()}images/{$color}" "Extracting ZIP file into {$this->mediaFilesystem->getAdapter()->getPathPrefix()}images/{$color}",
]); ]);
$zip->extractTo($this->mediaFilesystem->getAdapter()->getPathPrefix().'images'.DIRECTORY_SEPARATOR.$color); $zip->extractTo($this->mediaFilesystem->getAdapter()->getPathPrefix().'images'.DIRECTORY_SEPARATOR.$color);
$zip->close(); $zip->close();
@ -49,18 +49,17 @@ class ImageLoader extends BaseLoader
} }
} }
/** /**
* Load images of models * Load images of models.
*
*/ */
public function loadMissingModelImages() { public function loadMissingModelImages()
{
$models = $this->em->getRepository(Model::class)->findAll(); $models = $this->em->getRepository(Model::class)->findAll();
$this->initProgressBar(count($models)); $this->initProgressBar(count($models));
foreach ($models as $model) { foreach ($models as $model) {
$this->progressBar->setMessage($model->getNumber()); $this->progressBar->setMessage($model->getNumber());
if(!$this->mediaFilesystem->has('images'.DIRECTORY_SEPARATOR.'-1'.DIRECTORY_SEPARATOR.$model->getNumber().'.png')) { if (!$this->mediaFilesystem->has('images'.DIRECTORY_SEPARATOR.'-1'.DIRECTORY_SEPARATOR.$model->getNumber().'.png')) {
try { try {
$this->loadModelImage($this->mediaFilesystem->getAdapter()->getPathPrefix().$model->getPath()); $this->loadModelImage($this->mediaFilesystem->getAdapter()->getPathPrefix().$model->getPath());
} catch (\Exception $e) { } catch (\Exception $e) {
@ -73,14 +72,15 @@ class ImageLoader extends BaseLoader
} }
/** /**
* Render model and save image into co * Render model and save image into co.
* *
* @param $file * @param $file
*/ */
public function loadModelImage($file) { public function loadModelImage($file)
{
$this->stlRendererService->render( $this->stlRendererService->render(
$file, $file,
$this->mediaFilesystem->getAdapter()->getPathPrefix().'images'.DIRECTORY_SEPARATOR.'-1'.DIRECTORY_SEPARATOR $this->mediaFilesystem->getAdapter()->getPathPrefix().'images'.DIRECTORY_SEPARATOR.'-1'.DIRECTORY_SEPARATOR
); );
} }
} }

View File

@ -127,7 +127,7 @@ class ModelLoader extends BaseLoader
/** /**
* Load model entity and all related submodels into database while generating stl file of model. * Load model entity and all related submodels into database while generating stl file of model.
* Uses LDView to convert LDraw .dat to .stl * Uses LDView to convert LDraw .dat to .stl.
* *
* @param $file * @param $file
* *
@ -219,6 +219,7 @@ class ModelLoader extends BaseLoader
} }
} catch (ConvertingFailedException $e) { } catch (ConvertingFailedException $e) {
$this->logger->error($e->getMessage()); $this->logger->error($e->getMessage());
return null; return null;
} }
@ -273,8 +274,8 @@ class ModelLoader extends BaseLoader
return $context->getAdapter()->getPathPrefix().$filename; return $context->getAdapter()->getPathPrefix().$filename;
} }
// Try to find model in current LDRAW\PARTS sub-directory // Try to find model in current LDRAW\PARTS sub-directory
elseif($this->ldrawLibraryContext) { elseif ($this->ldrawLibraryContext) {
if($this->ldrawLibraryContext->has('parts/'.$filename)) { if ($this->ldrawLibraryContext->has('parts/'.$filename)) {
return $this->ldrawLibraryContext->getAdapter()->getPathPrefix().'parts'.DIRECTORY_SEPARATOR.$filename; return $this->ldrawLibraryContext->getAdapter()->getPathPrefix().'parts'.DIRECTORY_SEPARATOR.$filename;
} }
// Try to find model in current LDRAW\P sub-directory // Try to find model in current LDRAW\P sub-directory
@ -301,6 +302,7 @@ class ModelLoader extends BaseLoader
return new Filesystem($adapter); return new Filesystem($adapter);
} catch (Exception $exception) { } catch (Exception $exception) {
$this->logger->error($exception->getMessage()); $this->logger->error($exception->getMessage());
return null; return null;
} }
} }
@ -327,6 +329,7 @@ class ModelLoader extends BaseLoader
// Do not include models without permission to redistribute // Do not include models without permission to redistribute
elseif ($modelArray['license'] != 'Redistributable under CCAL version 2.0') { elseif ($modelArray['license'] != 'Redistributable under CCAL version 2.0') {
$this->logger->info('Model skipped.', ['number' => $modelArray['id'], 'license' => $modelArray['license']]); $this->logger->info('Model skipped.', ['number' => $modelArray['id'], 'license' => $modelArray['license']]);
return false; return false;
} }

View File

@ -39,7 +39,8 @@ class RelationLoader extends BaseLoader
$this->load($parts); $this->load($parts);
} }
private function load($parts) { private function load($parts)
{
$this->initProgressBar(count($parts)); $this->initProgressBar(count($parts));
/** @var Part $part */ /** @var Part $part */
foreach ($parts as $part) { foreach ($parts as $part) {

View File

@ -5,7 +5,6 @@ namespace AppBundle\Service;
use AppBundle\Exception\ConvertingFailedException; use AppBundle\Exception\ConvertingFailedException;
use AppBundle\Exception\FileNotFoundException; use AppBundle\Exception\FileNotFoundException;
use AppBundle\Exception\RenderFailedException; use AppBundle\Exception\RenderFailedException;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
use Symfony\Component\Process\ProcessBuilder; use Symfony\Component\Process\ProcessBuilder;
@ -38,6 +37,7 @@ class StlRendererService
/** /**
* StlRendererService constructor. * StlRendererService constructor.
*
* @param $layout * @param $layout
* @param $povray * @param $povray
* @param $stl2pov * @param $stl2pov
@ -48,55 +48,59 @@ class StlRendererService
$this->povray = $povray; $this->povray = $povray;
$this->layout = $layout; $this->layout = $layout;
$this->size = 900; $this->size = 900;
if($tmpDir) { if ($tmpDir) {
$this->tmpDir = $tmpDir; $this->tmpDir = $tmpDir;
} else { } else {
$this->tmpDir = sys_get_temp_dir(); $this->tmpDir = sys_get_temp_dir();
} }
} }
/** /**
* @param $file * @param $file
* @param $destinationDir * @param $destinationDir
* @param bool $cleanup * @param bool $cleanup
* @return string *
* @throws \Exception * @throws \Exception
*
* @return string
*/ */
public function render($file, $destinationDir, $cleanup = true) { public function render($file, $destinationDir, $cleanup = true)
{
$povFile = $this->convertStlPov($file); $povFile = $this->convertStlPov($file);
try { try {
$image = $this->renderPov($povFile, $destinationDir); $image = $this->renderPov($povFile, $destinationDir);
if($cleanup) { if ($cleanup) {
unlink($povFile); unlink($povFile);
} }
return $image;
return $image;
} catch (\Exception $exception) { } catch (\Exception $exception) {
unlink($povFile); unlink($povFile);
throw $exception; throw $exception;
} }
} }
/** /**
* Converts STL file to pov scene by calling stl2pov command line application * Converts STL file to pov scene by calling stl2pov command line application.
* *
* Generated file is saved to tmp directory specifed in constructor of this class and path to file is returned * Generated file is saved to tmp directory specifed in constructor of this class and path to file is returned
* *
* stl2pov (version 3.3.0) - https://github.com/rsmith-nl/stltools/releases/tag/3.3 * stl2pov (version 3.3.0) - https://github.com/rsmith-nl/stltools/releases/tag/3.3
* *
* @param string $file The full path to stl file * @param string $file The full path to stl file
* @return string Return the full path to the generated pov scene *
* @throws ConvertingFailedException throws exception if there are problems converting stl file to pov * @throws ConvertingFailedException throws exception if there are problems converting stl file to pov
* @throws FileNotFoundException throws exception if source file not found * @throws FileNotFoundException throws exception if source file not found
*
* @return string Return the full path to the generated pov scene
*/ */
private function convertStlPov($file) { private function convertStlPov($file)
if(!file_exists($file)) { {
if (!file_exists($file)) {
throw new FileNotFoundException($file); throw new FileNotFoundException($file);
} }
if(pathinfo($file, PATHINFO_EXTENSION) != 'stl') { if (pathinfo($file, PATHINFO_EXTENSION) != 'stl') {
throw new ConvertingFailedException($file, 'POV', 'Wrong input filetype'); throw new ConvertingFailedException($file, 'POV', 'Wrong input filetype');
} }
@ -111,7 +115,7 @@ class StlRendererService
$processBuilder = new ProcessBuilder(); $processBuilder = new ProcessBuilder();
$process = $processBuilder->setPrefix($this->stl2pov) $process = $processBuilder->setPrefix($this->stl2pov)
->setArguments([ ->setArguments([
$file $file,
]) ])
->getProcess(); ->getProcess();
$process->mustRun(); $process->mustRun();
@ -122,9 +126,9 @@ class StlRendererService
} }
// Load contents of .inc file to variable // Load contents of .inc file to variable
$incFile = file_get_contents($filename.'.inc',LOCK_EX); $incFile = file_get_contents($filename.'.inc', LOCK_EX);
// Replace mesh name in loaded inc file to match declaration in scene layout // Replace mesh name in loaded inc file to match declaration in scene layout
$incFile = preg_replace('/# declare m_(.*) = mesh/','#declare m_MYSOLID = mesh',$incFile); $incFile = preg_replace('/# declare m_(.*) = mesh/', '#declare m_MYSOLID = mesh', $incFile);
// Remove no longer needed inc file // Remove no longer needed inc file
unlink($filename.'.inc'); unlink($filename.'.inc');
@ -140,7 +144,7 @@ class StlRendererService
if (!file_put_contents($outputFile, $incFile, LOCK_EX)) { if (!file_put_contents($outputFile, $incFile, LOCK_EX)) {
throw new ConvertingFailedException($file, 'POV'); throw new ConvertingFailedException($file, 'POV');
} }
if(!file_put_contents($outputFile, $layout, FILE_APPEND | LOCK_EX)) { if (!file_put_contents($outputFile, $layout, FILE_APPEND | LOCK_EX)) {
throw new ConvertingFailedException($file, 'POV'); throw new ConvertingFailedException($file, 'POV');
} }
if (!file_exists($outputFile)) { if (!file_exists($outputFile)) {
@ -150,20 +154,22 @@ class StlRendererService
return $outputFile; return $outputFile;
} }
/** /**
* Renders POV-Ray .pov file by calling povray command line application * Renders POV-Ray .pov file by calling povray command line application.
* *
* http://www.povray.org/ * http://www.povray.org/
* *
* @param string $file The full path to .pov file to be rendered * @param string $file The full path to .pov file to be rendered
* @param $to * @param $to
* @return string Full path to rendered image file *
* @throws RenderFailedException throws exception if there are problems rendering image * @throws RenderFailedException throws exception if there are problems rendering image
* @throws FileNotFoundException throws exception if source file not found * @throws FileNotFoundException throws exception if source file not found
*
* @return string Full path to rendered image file
*/ */
private function renderPov($file, $to) { private function renderPov($file, $to)
if(!file_exists($file)) { {
if (!file_exists($file)) {
throw new FileNotFoundException($file); throw new FileNotFoundException($file);
} }
@ -185,20 +191,21 @@ class StlRendererService
$process = $processBuilder->setPrefix($this->povray) $process = $processBuilder->setPrefix($this->povray)
->setArguments([ ->setArguments([
"+I\"{$file}\"", "+I\"{$file}\"",
"+FN", '+FN',
"+W{$this->size}", "+W{$this->size}",
"+H{$this->size}", "+H{$this->size}",
"+O\"$outputFile\"", "+O\"$outputFile\"",
"+Q8", '+Q8',
"+AM2", '+AM2',
"+A0.5", '+A0.5',
"-D", '-D',
])->getProcess(); ])->getProcess();
$process->mustRun(); $process->mustRun();
if(!file_exists($outputFile)) { if (!file_exists($outputFile)) {
throw new RenderFailedException("{$to}{$filename}.png"); throw new RenderFailedException("{$to}{$filename}.png");
} }
return $outputFile; return $outputFile;
} }
} }

View File

@ -2,17 +2,24 @@
namespace AppBundle\Transformer; namespace AppBundle\Transformer;
class FormatTransformer class FormatTransformer
{ {
function bytesToSize($bytes, $precision = 2) /**
* Transform bytes count to human readable format.
*
* @param $bytes
* @param int $precision
* @return string
*/
public function bytesToSize($bytes, $precision = 2)
{ {
if ($bytes == 0) if ($bytes == 0) {
return "0.00 B"; return '0.00 B';
}
$suffix = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); $suffix = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$exponent = floor(log($bytes, 1024)); $exponent = floor(log($bytes, 1024));
return round($bytes/pow(1024, $exponent), $precision).' '.$suffix[(int)$exponent]; return round($bytes / pow(1024, $exponent), $precision).' '.$suffix[(int) $exponent];
} }
} }

View File

@ -47,7 +47,7 @@ class LDModelParser
]; ];
$firstLine = false; $firstLine = false;
foreach(explode("\n", $string) as $line) { foreach (explode("\n", $string) as $line) {
$line = trim($line); $line = trim($line);
// Comments or META Commands // Comments or META Commands
@ -71,7 +71,7 @@ class LDModelParser
$keywords = explode(',', preg_replace('/^!KEYWORDS /', '', $line)); $keywords = explode(',', preg_replace('/^!KEYWORDS /', '', $line));
foreach ($keywords as $keyword) { foreach ($keywords as $keyword) {
$keyword = trim($keyword); $keyword = trim($keyword);
if($keyword) { if ($keyword) {
$model['keywords'][] = $keyword; $model['keywords'][] = $keyword;
} }
} }
@ -113,7 +113,7 @@ class LDModelParser
$model['subparts'][$id][$color] = 1; $model['subparts'][$id][$color] = 1;
} }
} elseif (!empty($line) && !in_array($line[0], ['2', '3', '4', '5'])) { } elseif (!empty($line) && !in_array($line[0], ['2', '3', '4', '5'])) {
throw new ErrorParsingLineException($model['id'],$line); throw new ErrorParsingLineException($model['id'], $line);
} }
} }

View File

@ -58,6 +58,7 @@ class RelationMapper
private function loadResource($file, $domain) private function loadResource($file, $domain)
{ {
try { try {
$this->relations[$domain] = [];
$this->relations[$domain] = Yaml::parse(file_get_contents($file->getPathname())); $this->relations[$domain] = Yaml::parse(file_get_contents($file->getPathname()));
} catch (ParseException $e) { } catch (ParseException $e) {
throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $file->getPathname()), 0, $e); throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $file->getPathname()), 0, $e);

View File

@ -1,61 +0,0 @@
<?php
namespace AppBundle\Utils;
class Stats
{
private $success;
private $error;
private $skipped;
/**
* Stats constructor.
*/
public function __construct()
{
$this->skipped = 0;
$this->error = 0;
$this->success = 0;
}
public function success()
{
$this->success = $this->success + 1;
}
public function error()
{
$this->error = $this->error + 1;
}
public function skipped()
{
$this->skipped = $this->skipped + 1;
}
/**
* @return int
*/
public function getSuccess()
{
return $this->success;
}
/**
* @return int
*/
public function getError()
{
return $this->error;
}
/**
* @return int
*/
public function getSkipped()
{
return $this->skipped;
}
}