1
0
mirror of https://github.com/ToxicCrack/PrintABrick.git synced 2025-05-27 17:30:07 -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;
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()
{
if(!$data = unserialize($this->cache->fetch('themes')))
{
$data = $this->bricksetClient->getThemes();
if (!$data = unserialize($this->cache->fetch('themes'))) {
$data = $this->bricksetClient->getThemes();
$this->cache->save('themes', serialize($data), self::CACHE_LIFETIME);
}
@ -40,11 +39,10 @@ class BricksetManager
public function getSubthemesByTheme($theme)
{
$key = "subthemes-".$theme;
$key = 'subthemes-'.$theme;
if(!$data = unserialize($this->cache->fetch($key)))
{
$data = $this->bricksetClient->getSubthemes($theme);
if (!$data = unserialize($this->cache->fetch($key))) {
$data = $this->bricksetClient->getSubthemes($theme);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
}
@ -53,11 +51,10 @@ class BricksetManager
public function getYearsByTheme($theme)
{
$key = "years-".$theme;
$key = 'years-'.$theme;
if(!$data = unserialize($this->cache->fetch($key)))
{
$data = $this->bricksetClient->getYears($theme);
if (!$data = unserialize($this->cache->fetch($key))) {
$data = $this->bricksetClient->getYears($theme);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
}
@ -66,9 +63,9 @@ class BricksetManager
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);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
}
@ -78,10 +75,9 @@ class BricksetManager
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]);
$data = isset($sets[0]) ? $sets[0] : null;
@ -93,10 +89,9 @@ class BricksetManager
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);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
}
@ -106,10 +101,9 @@ class BricksetManager
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);
$this->cache->save($key, serialize($data), self::CACHE_LIFETIME);
}
@ -119,11 +113,10 @@ class BricksetManager
public function getAdditionalImages($id)
{
$key = "images-".$id;
$key = 'images-'.$id;
if(!$data = unserialize($this->cache->fetch($key)))
{
$data = $this->bricksetClient->getAdditionalImages($id);
if (!$data = unserialize($this->cache->fetch($key))) {
$data = $this->bricksetClient->getAdditionalImages($id);
$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);
}
// /**
// * Get a list of all parts (normal + spare) used in a set.
// *
// * @param $setId
// * @param $page
// *
// * @return
// */
// public function getSetParts($setId, $page = null)
// {
// $options = [
// 'query' => [
// 'page' => $page,
// ],
// ];
//
// $response = $this->rebrickableClient->call('GET', 'lego/sets/'.$setId.'/parts', $options);
// $data = json_decode($response, true)['results'];
//
// return $this->serializer->denormalize($data, Part::class.'[]', self::FORMAT);
// }
/**
* Get a list of all parts (normal + spare) used in a set.
*
* @param $setId
* @param $page
*
* @return
*/
public function getSetParts($setId, $page = null)
{
$options = [
'query' => [
'page' => $page,
],
];
$response = $this->rebrickableClient->call('GET', 'lego/sets/'.$setId.'/parts', $options);
$data = json_decode($response, true)['results'];
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([
'command' => 'app:load:models',
'ldraw' => $input->getArgument('ldraw'),
'--all' => true
]),$output);
'--all' => true,
]), $output);
if($returnCode) {
if ($returnCode) {
return 1;
}
$loadRebrickableCommad = $this->getApplication()->find('app:load:rebrickable');
$returnCode = $loadRebrickableCommad->run(new ArrayInput([
'command' => 'app:load:rebrickable']),$output);
'command' => 'app:load:rebrickable', ]), $output);
if($returnCode) {
if ($returnCode) {
return 1;
}
$loadRelationsCommand = $this->getApplication()->find('app:load:relations');
$returnCode = $loadRelationsCommand->run(new ArrayInput([
'command' => 'app:load:relations']),$output);
'command' => 'app:load:relations', ]), $output);
if($returnCode) {
if ($returnCode) {
return 1;
}
$loadImagesCommand = $this->getApplication()->find('app:load:images');
$returnCode = $loadImagesCommand->run(new ArrayInput([
'command' => 'app:load:images',
'--color' => -1,
'--rebrickable' => true,
'--models' => true
]),$output);
'command' => 'app:load:images',
'--color' => -1,
'--rebrickable' => true,
'--models' => true,
]), $output);
return 0;
}
}

View File

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

View File

@ -34,6 +34,7 @@ class LoadModelsCommand extends ContainerAwareCommand
{
if (!$this->lock()) {
$output->writeln('The command is already running in another process.');
return 1;
}
@ -43,8 +44,9 @@ class LoadModelsCommand extends ContainerAwareCommand
$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');
return 1;
}
@ -86,6 +88,7 @@ class LoadModelsCommand extends ContainerAwareCommand
} else {
$output->writeln("<error>{$ldraw} is not a valid path!</error>");
$this->release();
return 1;
}

View File

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

View File

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

View File

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

View File

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

View File

@ -39,25 +39,25 @@ class SearchController extends Controller
{
$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 = [];
/** @var Model $model */
foreach ($modelsResult as $model) {
$models[] = [
'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 = [];
/** @var Set $set */
foreach ($setsResult as $set) {
$sets[] = [
'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' => [
'name' => 'Models',
'results' => $models,
]
]
],
],
]);
return $response;
}
}
}

View File

@ -8,7 +8,7 @@ class ErrorParsingLineException extends FileException
{
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);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -69,8 +69,8 @@ abstract class BaseLoader
protected function initProgressBar($total, $format = 'loader')
{
$this->progressBar = new ProgressBar($this->output, $total);
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('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);
$this->progressBar->setFormat($format);
$this->progressBar->setBarWidth(70);
@ -83,12 +83,12 @@ abstract class BaseLoader
case STREAM_NOTIFY_FILE_SIZE_IS:
$this->initProgressBar($bytes_max);
$this->progressBar->setFormat('download');
$this->progressBar->setMessage($this->formatTransformer->bytesToSize($bytes_max),'size');
$this->progressBar->setRedrawFrequency(1024*1024);
$this->progressBar->setMessage($this->formatTransformer->bytesToSize($bytes_max), 'size');
$this->progressBar->setRedrawFrequency(1024 * 1024);
break;
case STREAM_NOTIFY_PROGRESS:
$this->progressBar->setProgress($bytes_transferred);
$this->progressBar->setMessage($this->formatTransformer->bytesToSize($bytes_transferred),'progress');
$this->progressBar->setMessage($this->formatTransformer->bytesToSize($bytes_transferred), 'progress');
break;
case STREAM_NOTIFY_COMPLETED:
$this->progressBar->finish();
@ -128,8 +128,10 @@ abstract class BaseLoader
return $temp;
}
protected function writeOutput(array $lines) {
if($this->output)
protected function writeOutput(array $lines)
{
if ($this->output) {
$this->output->writeln($lines);
}
}
}

View File

@ -30,16 +30,16 @@ class ImageLoader extends BaseLoader
*/
public function loadColorFromRebrickable($color, $path = null)
{
if(!$path) {
if (!$path) {
$path = $this->rebrickableDownloadUrl."ldraw/parts_{$color}.zip";
}
$file = $this->downloadFile($path);
$zip = new \ZipArchive($file);
if ($zip->open($file) === TRUE) {
if ($zip->open($file) === true) {
$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->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();
$this->initProgressBar(count($models));
foreach ($models as $model) {
$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 {
$this->loadModelImage($this->mediaFilesystem->getAdapter()->getPathPrefix().$model->getPath());
} 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
*/
public function loadModelImage($file) {
public function loadModelImage($file)
{
$this->stlRendererService->render(
$file,
$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.
* Uses LDView to convert LDraw .dat to .stl
* Uses LDView to convert LDraw .dat to .stl.
*
* @param $file
*
@ -219,6 +219,7 @@ class ModelLoader extends BaseLoader
}
} catch (ConvertingFailedException $e) {
$this->logger->error($e->getMessage());
return null;
}
@ -273,8 +274,8 @@ class ModelLoader extends BaseLoader
return $context->getAdapter()->getPathPrefix().$filename;
}
// Try to find model in current LDRAW\PARTS sub-directory
elseif($this->ldrawLibraryContext) {
if($this->ldrawLibraryContext->has('parts/'.$filename)) {
elseif ($this->ldrawLibraryContext) {
if ($this->ldrawLibraryContext->has('parts/'.$filename)) {
return $this->ldrawLibraryContext->getAdapter()->getPathPrefix().'parts'.DIRECTORY_SEPARATOR.$filename;
}
// Try to find model in current LDRAW\P sub-directory
@ -301,6 +302,7 @@ class ModelLoader extends BaseLoader
return new Filesystem($adapter);
} catch (Exception $exception) {
$this->logger->error($exception->getMessage());
return null;
}
}
@ -327,6 +329,7 @@ class ModelLoader extends BaseLoader
// Do not include models without permission to redistribute
elseif ($modelArray['license'] != 'Redistributable under CCAL version 2.0') {
$this->logger->info('Model skipped.', ['number' => $modelArray['id'], 'license' => $modelArray['license']]);
return false;
}

View File

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

View File

@ -5,7 +5,6 @@ namespace AppBundle\Service;
use AppBundle\Exception\ConvertingFailedException;
use AppBundle\Exception\FileNotFoundException;
use AppBundle\Exception\RenderFailedException;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\ProcessBuilder;
@ -38,6 +37,7 @@ class StlRendererService
/**
* StlRendererService constructor.
*
* @param $layout
* @param $povray
* @param $stl2pov
@ -48,55 +48,59 @@ class StlRendererService
$this->povray = $povray;
$this->layout = $layout;
$this->size = 900;
if($tmpDir) {
if ($tmpDir) {
$this->tmpDir = $tmpDir;
} else {
$this->tmpDir = sys_get_temp_dir();
}
}
/**
* @param $file
* @param $destinationDir
* @param bool $cleanup
* @return string
*
* @throws \Exception
*
* @return string
*/
public function render($file, $destinationDir, $cleanup = true) {
public function render($file, $destinationDir, $cleanup = true)
{
$povFile = $this->convertStlPov($file);
try {
$image = $this->renderPov($povFile, $destinationDir);
if($cleanup) {
if ($cleanup) {
unlink($povFile);
}
return $image;
return $image;
} catch (\Exception $exception) {
unlink($povFile);
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
*
* stl2pov (version 3.3.0) - https://github.com/rsmith-nl/stltools/releases/tag/3.3
*
* @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 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) {
if(!file_exists($file)) {
private function convertStlPov($file)
{
if (!file_exists($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');
}
@ -111,7 +115,7 @@ class StlRendererService
$processBuilder = new ProcessBuilder();
$process = $processBuilder->setPrefix($this->stl2pov)
->setArguments([
$file
$file,
])
->getProcess();
$process->mustRun();
@ -122,9 +126,9 @@ class StlRendererService
}
// 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
$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
unlink($filename.'.inc');
@ -140,7 +144,7 @@ class StlRendererService
if (!file_put_contents($outputFile, $incFile, LOCK_EX)) {
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');
}
if (!file_exists($outputFile)) {
@ -150,20 +154,22 @@ class StlRendererService
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/
*
* @param string $file The full path to .pov file to be rendered
* @param $to
* @return string Full path to rendered image file
*
* @throws RenderFailedException throws exception if there are problems rendering image
* @throws FileNotFoundException throws exception if source file not found
*
* @return string Full path to rendered image file
*/
private function renderPov($file, $to) {
if(!file_exists($file)) {
private function renderPov($file, $to)
{
if (!file_exists($file)) {
throw new FileNotFoundException($file);
}
@ -185,20 +191,21 @@ class StlRendererService
$process = $processBuilder->setPrefix($this->povray)
->setArguments([
"+I\"{$file}\"",
"+FN",
'+FN',
"+W{$this->size}",
"+H{$this->size}",
"+O\"$outputFile\"",
"+Q8",
"+AM2",
"+A0.5",
"-D",
'+Q8',
'+AM2',
'+A0.5',
'-D',
])->getProcess();
$process->mustRun();
if(!file_exists($outputFile)) {
if (!file_exists($outputFile)) {
throw new RenderFailedException("{$to}{$filename}.png");
}
return $outputFile;
}
}
}

View File

@ -2,17 +2,24 @@
namespace AppBundle\Transformer;
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)
return "0.00 B";
if ($bytes == 0) {
return '0.00 B';
}
$suffix = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
$suffix = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$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;
foreach(explode("\n", $string) as $line) {
foreach (explode("\n", $string) as $line) {
$line = trim($line);
// Comments or META Commands
@ -71,7 +71,7 @@ class LDModelParser
$keywords = explode(',', preg_replace('/^!KEYWORDS /', '', $line));
foreach ($keywords as $keyword) {
$keyword = trim($keyword);
if($keyword) {
if ($keyword) {
$model['keywords'][] = $keyword;
}
}
@ -113,7 +113,7 @@ class LDModelParser
$model['subparts'][$id][$color] = 1;
}
} 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)
{
try {
$this->relations[$domain] = [];
$this->relations[$domain] = Yaml::parse(file_get_contents($file->getPathname()));
} catch (ParseException $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;
}
}