Completed
Pull Request — master (#374)
by Leny
06:07
created

LoadFixtureData::load()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 24
rs 8.9713
c 1
b 0
f 0
cc 1
eloc 15
nc 1
nop 1
1
<?php
2
3
namespace Acme\AppBundle\DataFixtures\Seeds\ORM;
4
5
use Doctrine\Common\DataFixtures\AbstractFixture;
6
use Doctrine\Common\Persistence\ObjectManager;
7
use Nelmio\Alice\Fixtures;
8
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
9
use Symfony\Component\DependencyInjection\ContainerInterface;
10
11
/**
12
 * Load fixtures.
13
 */
14
class LoadFixtureData extends AbstractFixture implements ContainerAwareInterface
15
{
16
    /** @var ContainerInterface */
17
    private $container;
18
    private $fileLocator;
19
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public function setContainer(ContainerInterface $container = null)
24
    {
25
        $this->container = $container;
26
        $this->fileLocator = $this->container->get('file_locator');
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function load(ObjectManager $manager)
33
    {
34
        // Load fixtures files
35
    $files = [];
36
37
        $files['user'] = $this->fileLocator->locate('@AcmeAppBundle/DataFixtures/Seeds/ORM/User/user.yml');
38
        $files['folder'] = $this->fileLocator->locate('@AcmeAppBundle/DataFixtures/Seeds/ORM/Media/folder.yml');
39
        $files['template'] = $this->fileLocator->locate('@AcmeAppBundle/DataFixtures/Seeds/ORM/View/template.yml');
40
        $files['page'] = $this->fileLocator->locate('@AcmeAppBundle/DataFixtures/Seeds/ORM/View/page.yml');
41
        $files['i18n'] = $this->fileLocator->locate('@AcmeAppBundle/DataFixtures/Seeds/ORM/View/i18n.yml');
42
        $files['errorPage'] = $this->fileLocator->locate('@AcmeAppBundle/DataFixtures/Seeds/ORM/View/errorPage.yml');
43
44
        Fixtures::load(
45
        $files,
46
        $manager,
47
        [
48
        'providers'    => [$this],
49
        'locale'       => 'fr_FR',
50
        'persist_once' => false,
51
        ]
52
    );
53
54
        $manager->flush();
55
    }
56
57
    /**
58
     * Return random gender.
59
     *
60
     * @return string
61
     */
62
    public function gender()
63
    {
64
        $genders = [
65
        'male',
66
        'female',
67
    ];
68
69
        return $genders[array_rand($genders)];
70
    }
71
72
    /**
73
     * Return an image path for a new image.
74
     *
75
     * @param string $dir    The upload dir.
76
     * @param int    $width  The image width.
77
     * @param int    $height The image height.
78
     * @param string $type   The image type.
79
     *
80
     * @return string
81
     */
82
    public function image($dir, $width = null, $height = null, $type = '')
83
    {
84
        $originalWidth = $width ?: 'rand';
85
        $originalHeight = $height ?: 'rand';
86
        $rootDir = $this->container->get('kernel')->getRootDir().'/../web';
87
88
        $existingImages = glob($rootDir.'/'.$dir.'/*.png');
89
    // print_r($existingImages);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
90
    if ($matches = preg_grep('/'.$originalWidth.'-'.$originalHeight.'.png/', $existingImages)) {
91
        if (count($matches) > 30) {
92
            $image = array_rand($matches);
93
94
            return $image;
95
        }
96
    }
97
98
        $width = $width ?: rand(100, 300);
99
        $height = $height ?: rand(100, 300);
100
101
        $fileName = uniqid();
102
        $imageName = sprintf($rootDir.'/%s/%s-%s-%s.png', $dir, $fileName, $originalWidth, $originalHeight);
103
        $image = sprintf('http://%s/%d/%d/%s', 'lorempixel.com', $width, $height, $type);
104
105
        if (!is_dir(dirname($imageName))) {
106
            mkdir(dirname($imageName), 0777, true);
107
        }
108
        file_put_contents($imageName, file_get_contents($image));
109
        $imagePath = $dir.'/'.$fileName.'.png';
110
111
        return $imagePath;
112
    }
113
114
    /**
115
     * Return an image path for a new image.
116
     *
117
     * @param string $dir The upload dir.
118
     *
119
     * @return string
120
     */
121
    public function pdf($dir)
122
    {
123
        $rootDir = $this->container->get('kernel')->getRootDir().'/../web';
124
125
        $fileName = uniqid();
126
        $pdfName = sprintf($rootDir.'/%s/%s.pdf', $dir, $fileName);
127
        $pdf = $this->fileLocator->locate('@VictoireCoreBundle/DataFixtures/ORM/lorem.pdf');
128
129
        if (!is_dir(dirname($pdfName))) {
130
            mkdir(dirname($pdfName), 0777, true);
131
        }
132
        file_put_contents($pdfName, file_get_contents($pdf));
133
        $pdfPath = $dir.'/'.$fileName.'.pdf';
134
135
        return $pdfPath;
136
    }
137
138
    /**
139
     * Remove all files from given folder.
140
     *
141
     * @param string $folder Path of the folder to clear.
142
     *
143
     * @return void
144
     */
145
    public function clearFolder($folder)
146
    {
147
        if (is_dir($folder)) {
148
            // Open folder
149
        $openFolder = opendir($folder);
150
151
        // While folder is not empty
152
        while ($file = readdir($openFolder)) {
153
            if ($file != '.' && $file != '..') {
154
                // Remove file
155
            $recursiveDelete = function ($str) use (&$recursiveDelete) {
156
            if (is_file($str)) {
157
                return @unlink($str);
158
            } elseif (is_dir($str)) {
159
                $scan = glob(rtrim($str, '/').'/*');
160
                foreach ($scan as $path) {
161
                    $recursiveDelete($path);
162
                }
163
164
                return @rmdir($str);
165
            }
166
            };
167
                $recursiveDelete($folder.$file);
168
            }
169
        }
170
171
        // Close empty folder
172
        closedir($openFolder);
173
        }
174
    }
175
176
    /**
177
     * Replaces all question mark ('?') occurrences with a random letter uppercase.
178
     *
179
     * @param string $string String that needs to bet parsed.
180
     *
181
     * @return string
182
     */
183
    public static function lexifyUpper($string = '????')
184
    {
185
        return strtoupper(preg_replace_callback('/\?/', 'static::randomLetter', $string));
186
    }
187
188
    /**
189
     * Returns a random letter from a to z.
190
     *
191
     * @return string
192
     */
193
    public static function randomLetter()
194
    {
195
        return chr(mt_rand(97, 122));
196
    }
197
}
198