ListUserImagesCommand::humanFilesize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 10
1
<?php
2
/**
3
 * @author Rik van der Kemp <[email protected]>
4
 * @copyright Zicht Online <http://www.zicht.nl>
5
 */
6
7
namespace Zicht\Bundle\FrameworkExtraBundle\Command;
8
9
use Doctrine\ORM\EntityManager;
10
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
11
use Symfony\Component\Console\Input\InputArgument;
12
use Symfony\Component\Console\Input\InputInterface;
13
use Symfony\Component\Console\Input\InputOption;
14
use Symfony\Component\Console\Output\OutputInterface;
15
16
/**
17
 * Generates an overview of all images used in the defined Entity and the defined fields.
18
 *
19
 * Results are sorted by size descending.
20
 */
21
class ListUserImagesCommand extends ContainerAwareCommand
22
{
23
    /**
24
     * @{inheritDoc}
25
     */
26
    protected function configure()
27
    {
28
        $this
29
            ->setName('zicht:content:list-images')
30
            ->addArgument('entity', InputArgument::REQUIRED, 'The entity to query. Example: ZichtWebsiteBundle:Page:ContentPage ')
31
            ->addArgument('fields', InputArgument::REQUIRED, 'The fields to check for images, comma seperated. Example: body,teaser')
32
            ->addOption('concat', 'c', InputOption::VALUE_OPTIONAL, 'Optional concatenation string. Example: -c "CONCAT(\'http://www.krollermuller.nl/\', p.language, \'/\', p.id)" ')
33
            ->setDescription('List images used in specific fields of an Entity and show their file size.');
34
    }
35
36
    /**
37
     * @{inheritDoc}
38
     */
39
    protected function execute(InputInterface $input, OutputInterface $output)
40
    {
41
        /** @var EntityManager $em */
42
        $em = $this->getContainer()->get('doctrine')->getManager();
43
44
        $userFields = explode(',', $input->getArgument('fields'));
0 ignored issues
show
Bug introduced by
It seems like $input->getArgument('fields') can also be of type string[]; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

44
        $userFields = explode(',', /** @scrutinizer ignore-type */ $input->getArgument('fields'));
Loading history...
45
        $fields = [];
46
47
        foreach ($userFields as $fieldName) {
48
            $fields[$fieldName] = 'p.' . trim($fieldName);
49
        }
50
51
        if ('' !== $input->getOption('concat')) {
52
            $fields['custom'] = $input->getOption('concat') . ' as custom';
53
        }
54
55
        $dql = sprintf('SELECT p.id, %s FROM %s p', implode(', ', $fields), $input->getArgument('entity'));
0 ignored issues
show
Bug introduced by
It seems like $input->getArgument('entity') can also be of type string[]; however, parameter $args of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

55
        $dql = sprintf('SELECT p.id, %s FROM %s p', implode(', ', $fields), /** @scrutinizer ignore-type */ $input->getArgument('entity'));
Loading history...
56
57
        $qb = $em->createQuery($dql);
58
59
        if (array_key_exists('custom', $fields)) {
60
            unset($fields['custom']);
61
        }
62
63
        $list = [];
64
65
        foreach ($qb->getResult() as $record) {
66
            foreach (array_keys($fields) as $field) {
67
                if (preg_match_all('/\<img.*src=\"\/media(.*?)\".*\>/', $record[$field], $matches)) {
68
                    foreach ($matches[1] as $image) {
69
                        $imagePath = './web/media' . $image;
70
                        if (file_exists($imagePath)) {
71
                            $fileSize = filesize($imagePath);
72
                            $arr = [
73
                                'id' => $record['id'],
74
                                'image' => $image,
75
                                'size' => $this->humanFilesize($fileSize),
76
                            ];
77
78
                            if ('' !== $input->getOption('concat')) {
79
                                $arr['custom'] = $record['custom'];
80
                            }
81
82
                            $list[$fileSize][] = $arr;
83
                        } else {
84
                            $output->writeln('File not found ' . $image);
85
                        }
86
                    }
87
                }
88
            }
89
        }
90
91
        krsort($list);
92
93
        foreach ($list as $fileSize => $sizes) {
94
            foreach ($sizes as $size => $info) {
95
                $output->writeln(implode(', ', $info));
96
            }
97
        }
98
    }
99
100
    /**
101
     * Kindly ripped from PHP.net :P.
102
     *
103
     * @param string $bytes
104
     * @param int $decimals
105
     *
106
     * @return string
107
     */
108
    private function humanFilesize($bytes, $decimals = 2)
109
    {
110
        $sz = 'BKMGTP';
111
        $factor = (int)floor((strlen($bytes) - 1) / 3);
112
113
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
114
    }
115
}
116