]> Raphaël G. Git Repositories - blogbundle/blob - Fixture/BlogFixture.php
0e3617076e65f6341f50827f0b0f1edf92eb7f9f
[blogbundle] / Fixture / BlogFixture.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys BlogBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\BlogBundle\Fixture;
13
14 use Doctrine\Bundle\FixturesBundle\Fixture;
15 use Doctrine\Persistence\ObjectManager;
16
17 use Rapsys\PackBundle\Util\SluggerUtil;
18
19 use Rapsys\BlogBundle\Entity\Civility;
20 use Rapsys\BlogBundle\Entity\Group;
21 use Rapsys\BlogBundle\Entity\User;
22 use Rapsys\BlogBundle\Entity\UserTranslation;
23 use Rapsys\BlogBundle\Entity\Keyword;
24 use Rapsys\BlogBundle\Entity\KeywordTranslation;
25 use Rapsys\BlogBundle\Entity\Article;
26 use Rapsys\BlogBundle\Entity\ArticleTranslation;
27
28 /**
29 * {@inheritDoc}
30 */
31 class BlogFixture extends Fixture {
32 /**
33 * @var Rapsys\PackBundle\Util\SluggerUtil
34 */
35 private SluggerUtil $slugger;
36
37 /**
38 * Constructor
39 */
40 public function __construct(SluggerUtil $slugger) {
41 //Set slugger
42 $this->slugger = $slugger;
43 }
44
45 /**
46 * {@inheritDoc}
47 */
48 public function load(ObjectManager $manager) {
49 //Civility tree
50 $civilityTree = [
51 'Mister',
52 'Madam',
53 'Miss'
54 ];
55
56 //Create titles
57 $civilitys = [];
58 foreach($civilityTree as $civilityData) {
59 $civility = new Civility($civilityData);
60 $manager->persist($civility);
61 $civilitys[$civilityData] = $civility;
62 unset($civility);
63 }
64
65 //Group tree
66 //XXX: ROLE_XXX is required by
67 $groupTree = [
68 'User',
69 'Admin'
70 ];
71
72 //Create groups
73 $groups = [];
74 foreach($groupTree as $groupData) {
75 $group = new Group($groupData);
76 $manager->persist($group);
77 $groups[$groupData] = $group;
78 unset($group);
79 }
80
81 //Flush to get the ids
82 $manager->flush();
83
84 //User tree
85 $userTree = [
86 [
87 'civility' => 'Mister',
88 'group' => 'Admin',
89 'mail' => 'blog@rapsys.eu',
90 'password' => 'test',
91 'forename' => 'Raphaël',
92 'surname' => 'Gertz',
93 'active' => true,
94 'enable' => false,
95 'pseudonym' => 'Rapsys',
96 'slug' => $this->slugger->slug('Raphaël Gertz (rapsys)'),
97 'translations' => [
98 'en_gb' => 'Raphaël Gertz, born in 1984, is a web developper since 2007. Interested in free software, since 2004, when he begin contributing to a linux distribution, known now as Mageia, some path has been traveled since then.',
99 'fr_fr' => 'Raphaël Gertz, né en 1984, est développeur web depuis 2007. Passionné par le monde du logiciel libre, depuis 2004, où il commence à contribuer à une distribution linux, connue maintenant sous le nom Mageia, un certain chemin a été parcouru dès lors.'
100 ]
101 ],
102 ];
103
104 //Create users
105 $users = [];
106 foreach($userTree as $userData) {
107 $user = new User($userData['mail'], $userData['password'], $civilitys[$userData['civility']], $userData['forename'], $userData['surname'], $userData['active'], $userData['enable'], $userData['pseudonym'], $userData['slug']);
108 $user->addGroup($groups[$userData['group']]);
109 $manager->persist($user);
110 //Flush to get the id
111 $manager->flush();
112 $users[$userData['mail']] = $user;
113 foreach($userData['translations'] as $locale => $description) {
114 $userTranslation = new UserTranslation($users[$userData['mail']], $locale, $description);
115 $manager->persist($userTranslation);
116 unset($userTranslation);
117 }
118 unset($user);
119 }
120
121 //Flush to get the ids
122 $manager->flush();
123
124 //Keyword tree
125 $keywordTree = [
126 'png' => [
127 'en_gb' => [
128 'title' => 'PNG',
129 'description' => 'Portable Network Graphics (PNG) is an raster graphics file open format that supports lossless data compression'
130 ],
131 'fr_fr' => [
132 'title' => 'PNG',
133 'description' => 'Le Portable Network Graphics (PNG) est un format ouvert d’images numériques, qui a été créé pour remplacer le format GIF, à l’époque propriétaire et dont la compression était soumise à un brevet'
134 ]
135 ],
136 'imagick' => [
137 'en_gb' => [
138 'title' => 'Imagick',
139 'description' => 'ImageMagick is a free and open-source software suite for displaying, converting, and editing raster image and vector image files'
140 ],
141 'fr_fr' => [
142 'title' => 'Imagick',
143 'description' => 'Image Magick est une collection de logiciels libres pour afficher, convertir et modifier des images numériques matricielles ou vectorielles dans de nombreux formats'
144 ]
145 ],
146 'image' => [
147 'en_gb' => [
148 'title' => 'Image',
149 'description' => 'An image is an artifact that depicts visual perception, for example, a photo or a two-dimensional picture, that has a similar appearance to some subject'
150 ],
151 'fr_fr' => [
152 'title' => 'Image',
153 'description' => 'Une image est une représentation visuelle, voire mentale, de quelque chose'
154 ]
155 ],
156 'varnish' => [
157 'en_gb' => [
158 'title' => 'Varnish',
159 'description' => 'Varnish is an HTTP cache server deployed as a reverse proxy between applications servers and clients'
160 ],
161 'fr_fr' => [
162 'title' => 'Varnish',
163 'description' => 'Varnish est un serveur de cache HTTP déployé en tant que proxy inverse entre les serveurs d\'application et les clients'
164 ]
165 ],
166 'webservice' => [
167 'en_gb' => [
168 'title' => 'Web service',
169 'description' => 'A web service is a service offered by an electronic device to another electronic device, communicating with each other via the World Wide Web'
170 ],
171 'fr_fr' => [
172 'title' => 'Service web',
173 'description' => 'Un service web, ou service de la toile, est un protocole d\'interface informatique de la famille des technologies web permettant la communication et l\'échange de données entre applications et systèmes hétérogènes'
174 ]
175 ],
176 'rest' => [
177 'en_gb' => [
178 'title' => 'REST',
179 'description' => 'Representational state transfer (REST) or RESTful web services are a way of providing interoperability between computer systems on the Internet'
180 ],
181 'fr_fr' => [
182 'title' => 'REST',
183 'description' => 'Representational state transfer (REST) ou services web RESTful est une manière de fournir de l\'intéropérabilité entre systèmes d\'information sur Internet'
184 ]
185 ],
186 'hateoas' => [
187 'en_gb' => [
188 'title' => 'HATEOAS',
189 'description' => 'HATEOAS, abbreviation of Hypermedia As The Engine Of Application State, is a constraint of the REST application architecture that distinguishes it from other network application architectures'
190 ],
191 'fr_fr' => [
192 'title' => 'HATEOAS',
193 'description' => 'HATEOAS, abréviation d\'Hypermedia As Engine of Application State, Hypermédia en tant que moteur de l\'état d\'application, constitue une contrainte de l\'architecture d\'application REST qui la distingue de la plupart des autres architectures d\'applications réseau'
194 ]
195 ],
196 'uri' => [
197 'en_gb' => [
198 'title' => 'URI',
199 'description' => 'In information technology, a Uniform Resource Identifier (URI) is a string of characters used to identify a resource'
200 ],
201 'fr_fr' => [
202 'title' => 'URI',
203 'description' => 'En technologie de l\'information, une URI, abréviation d\'Uniform Resource Identifier, Identifiant uniforme de ressource, est une chaine de caractères utilisée pour identifier une ressource'
204 ]
205 ],
206 'cidr' => [
207 'en_gb' => [
208 'title' => 'CIDR',
209 'description' => 'Classless Inter-Domain Routing, CIDR, is a method for aggregating IP addresses and route them'
210 ],
211 'fr_fr' => [
212 'title' => 'CIDR',
213 'description' => 'Routage inter-domaine sans classe, de l\'anglais Classless Inter-Domain Routing, CIDR, est une méthode pour agréger des adresses IP et les router'
214 ]
215 ],
216 'amazon' => [
217 'en_gb' => [
218 'title' => 'Amazon',
219 'description' => 'Amazon Elastic Compute Cloud or EC2 is an Amazon server renting service allowing third party to run their own web application'
220 ],
221 'fr_fr' => [
222 'title' => 'Amazon',
223 'description' => 'Amazon Elastic Compute Cloud ou EC2 est un service proposé par Amazon permettant à des tiers de louer des serveurs sur lesquels exécuter leurs propres applications web'
224 ]
225 ],
226 'php' => [
227 'en_gb' => [
228 'title' => 'PHP',
229 'description' => 'PHP: Hypertext Preprocessor, better known as PHP, is an open programming language, used mostly to produce dynamic web pages through an HTTP server'
230 ],
231 'fr_fr' => [
232 'title' => 'PHP',
233 'description' => 'PHP : Hypertext Preprocessor, plus connu sous son sigle PHP, est un langage de programmation libre, principalement utilisé pour produire des pages Web dynamiques via un serveur HTTP'
234 ]
235 ],
236 'mysql' => [
237 'en_gb' => [
238 'title' => 'MySQL',
239 'description' => 'MySQL is an open-source relational database management system, RDBMS'
240 ],
241 'fr_fr' => [
242 'title' => 'MySQL',
243 'description' => 'MySQL est un système de gestion de bases de données relationnelles libre'
244 ]
245 ],
246 'azure' => [
247 'en_gb' => [
248 'title' => 'Azure',
249 'description' => 'Microsoft Azure, formerly Windows Azure, is a cloud computing service created by Microsoft for building, testing, deploying, and managing applications and services through a global network of Microsoft-managed data centers'
250 ],
251 'fr_fr' => [
252 'title' => 'Azure',
253 'description' => 'Microsoft Azure, anciennement Windows Azure, est une plateforme applicative en nuage crée par Microsoft pour construire, tester, déployer et gérer des applications et services sur un réseau global de centres de données opéré par Microsoft'
254 ]
255 ],
256 'microsoft' => [
257 'en_gb' => [
258 'title' => 'Microsoft',
259 'description' => 'Microsoft Corporation is an american multinational technology company, founded in 1975 by Bill Gates and Paul Allen'
260 ],
261 'fr_fr' => [
262 'title' => 'Microsoft',
263 'description' => 'Microsoft Corporation est une multinationale informatique et micro-informatique américaine, fondée en 1975 par Bill Gates et Paul Allen'
264 ]
265 ]
266 ];
267
268 //Create 3 keywords
269 $keywords = [];
270 foreach($keywordTree as $name => $data) {
271 $keyword = new Keyword();
272 $manager->persist($keyword);
273 //Flush to get the id
274 $manager->flush();
275 $keywords[$name] = $keyword;
276 foreach($data as $locale => $translation) {
277 $keywordTranslation = new KeywordTranslation($keywords[$name], $locale, $translation['description'], $this->slugger->slug($translation['title']), $translation['title']);
278 $manager->persist($keywordTranslation);
279 unset($keywordTranslation);
280 }
281 unset($keyword);
282 }
283
284 //Flush to get the ids
285 $manager->flush();
286
287 //Article tree
288 $articleTree = [
289 [
290 'mail' => 'blog@rapsys.eu',
291 'keywords' => ['image', 'imagick', 'png'],
292 'translations' => [
293 'en_gb' => [
294 'title' => 'How to reliably detect PNG image transparency with PHP',
295 'description' => 'I recently had to find out if a PNG has transparency using PHP.
296 All the code I found didn\'t seemed to work correctly for the various kind of PNG I had to deal with.
297 Here is the function I used.',
298 'body' => 'I recently had to find out if a PNG has transparency using PHP.
299 All the code I found didn\'t seemed to work correctly for the various kind of PNG I had to deal with.
300
301 I finished using the following function:
302
303 ```php
304 function png_has_transparency($im) {
305 //Retrieve content from imagick object
306 $content = $im->getImageBlob();
307
308 //Detect 32-bit png (each pixel has tranparency level)
309 if (ord(substr($content, 25, 1)) & 4) {
310 //Fetch iterator
311 $p = $im->getPixelIterator();
312
313 //Loop on each row
314 foreach($p as $r) {
315 //Loop on each row pixel
316 foreach($r as $pix) {
317 //Check if pixel has partial transparency
318 if ($pix->getColorValue(Imagick::COLOR_ALPHA) != 1) {
319 return true;
320 }
321 }
322 }
323 //Check 8-bit png transparency
324 } elseif (stripos($content, \'PLTE\') !== false || stripos($content, \'tRNS\') !== false) {
325 return true;
326 }
327
328 //Didn\'t found clue of transparency
329 return false;
330 }
331 ```
332
333 This function works with the only two transparency possibilities: 8 and 32-bit PNG.
334
335 The first case is a 32-bit PNG with transparency enabled, we have then to check every pixel to detect if it has transparent part or not.
336
337 The second case is a 8-bit PNG, then we only have to look the file content for transparency markers.
338
339 In this function configuration, we only read part of the file in 32-bit PNG until we detect one transparent pixel or parse content until transparency marker is detected in 8-bit PNG.
340
341 The worst case scenario will be 32-bit PNG with transparency flag without transparency or 8-bit PNG without transparency flag.
342
343 Depending on how likely you are to have transparency in each cases you might want to reverse the flow of this function.
344
345 Big thanks to these articles which expains how these parts work in a bit more detail:
346 - <https://www.jonefox.com/blog/2011/04/15/how-to-detect-transparency-in-png-images>
347 - <http://camendesign.com/code/uth1_is-png-32bit>
348 - <https://stackoverflow.com/questions/5495275/how-to-check-if-an-image-has-transparency-using-gd>
349
350 Hope this helps someone else out there.'
351 ],
352 'fr_fr' => [
353 'title' => 'Comment détecter la tranparence dans des images PNG en PHP de manière fiable',
354 'description' => 'J\'ai récemment du trouver comment détecter en PHP les images PNG transparentes.
355 Les codes trouvés ne semblaient pas fonctionner de manière satisfaisante pour les différents types de PNG à contrôler.
356 Voici la fonction que j\'ai fini par utiliser.',
357 'body' => 'J\'ai récemment du trouver comment détecter en PHP les images PNG transparentes.
358 Les codes trouvés ne semblaient pas fonctionner de manière satisfaisante pour les différents types de PNG à contrôler.
359 J\'ai fini par utiliser la fonction suivante:
360
361 ```php
362 function png_has_transparency($im) {
363 //Retrieve content from imagick object
364 $content = $im->getImageBlob();
365
366 //Detect 32bit png (each pixel has tranparency level)
367 if (ord(substr($content, 25, 1)) & 4) {
368 //Fetch iterator
369 $p = $im->getPixelIterator();
370
371 //Loop on each row
372 foreach($p as $r) {
373 //Loop on each row pixel
374 foreach($r as $pix) {
375 //Check if pixel has partial transparency
376 if ($pix->getColorValue(Imagick::COLOR_ALPHA) != 1) {
377 return true;
378 }
379 }
380 }
381 //Check 8bit png transparency
382 } elseif (stripos($content, \'PLTE\') !== false || stripos($content, \'tRNS\') !== false) {
383 return true;
384 }
385
386 //Didn\'t found clue of transparency
387 return false;
388 }
389 ```
390
391 Cette fonction fonctionne avec les deux seules possibilités : PNG 8 et 32 bits.
392
393 Le premier cas est un PNG 32 bits avec transparence activée, on doit alors vérifier l\'opacité de chaque pixel savoir si l\'image a de la transparence ou non.
394
395 Le second cas est un PNG 8 bits, on a simplement à détecter un marqueur de transparence dans le contenu du fichier.
396
397 Dans cette configuration de fonction, on lit seulement une partie du PNG 32 bits jusqu\'à détection d\'un pixel transparent où on analyse le contenu jusqu\'à trouver un marqueur de transparence dans un PNG 8 bits.
398
399 Les pires cas seront un PNG 32 bits avec marqueur de transparence sans pixel transparent ou PNG 8 bits sans marqueur de transparence.
400
401 Selon les probabilités de rencontrer les différents cas de transparence vous pouvez être intéressé pour renverser l\'ordre des tests de cette fonction.
402
403 Un grand merci à ces articles qui expliquent plus en détail comment fonctionnent les différentes parties de ce code:
404 - <https://www.jonefox.com/blog/2011/04/15/how-to-detect-transparency-in-png-images>
405 - <http://camendesign.com/code/uth1_is-png-32bit>
406 - <https://stackoverflow.com/questions/5495275/how-to-check-if-an-image-has-transparency-using-gd>
407
408 En espérant que cela puisse aider quelques personnes.'
409 ]
410 ]
411 ],
412 [
413 'mail' => 'blog@rapsys.eu',
414 'keywords' => ['hateoas', 'rest', 'uri', 'varnish', 'webservice'],
415 'translations' => [
416 'en_gb' => [
417 'title' => 'Caching webservice with varnish',
418 'description' => 'I recently had to find a way to cache a webservice anwsers.
419 Here is the Varnish configuration fitting my needs.',
420 'body' => 'I recently had to find a way to cache a webservice anwsers.
421
422 The webservice is a RESTfull API serving as a gateway between a private HATEOAS API and a client generating more than 500 000 requests a day.
423
424 The first surprise is that if your well educated client, sending you a header Authorization: Bearer, will not be cached by default by Varnish !
425
426 Let\'s force back the standard behaviour with this header for our webservice uri prefix:
427
428 ```varnish
429 sub vcl_recv {
430 # Force cache response even with req.http.Authorization set
431 if (req.http.Authorization) {
432 if (req.url ~ "^/webservice/uri/prefix/") {
433 return (lookup);
434 }
435 }
436 }
437 ```
438
439 This has security implication, because anyone allowed to request varnish will be able to retrieve a cached result without authentification.
440
441 It is important to validate the Authorization header value before serving the result from cache.
442
443 Now, our webservice has three possibles answers :
444 - 200: the data in JSON
445 - 404: data was not found
446 - 410: data is not available anymore
447
448 Let\'s cache our results depending on the reponse code:
449
450 ```varnish
451 sub vcl_fetch {
452 if (req.url ~ "^/webservice/uri/prefix/") {
453 if (beresp.status == 404) {
454 set beresp.ttl = 7d;
455 }
456 if (beresp.status == 410) {
457 set beresp.ttl = 7d;
458 }
459 if (beresp.status == 200) {
460 set beresp.ttl = 24h;
461 }
462 }
463 }
464 ```
465
466 With this configuration, we divided by 5 the quantity of request on our gateway from the client who was not able to cache our result himself.'
467 ],
468 'fr_fr' => [
469 'title' => 'Mise en cache de webservice avec varnish',
470 'description' => 'J\'ai eu récemment à trouver comment mettre en cache les réponses d\'un webservice.
471 Voici la configuration varnish qui a répondu à mes besoins.',
472 'body' => 'J\'ai eu récemment à trouver comment mettre en cache les réponses d\'un webservice.
473
474 L\'API RESTfull du webservice sert de passerelle entre un API privé HATEOAS et un client générant plus de 500 000 requêtes par jour.
475
476 La première surprise est qu\'un client bien élevé, envoyant un en-tête Authorization: Bearer, ne sera pas mis en cache par Varnish par défaut !
477
478 Forçons le fonctionnement standard avec l\'en-tête pour le préfixe de l\'uri de notre webservice:
479
480 ```varnish
481 sub vcl_recv {
482 # Force la mise en cache de la réponse même avec req.http.Authorization présent
483 if (req.http.Authorization) {
484 if (req.url ~ "^/webservice/uri/prefix/") {
485 return (lookup);
486 }
487 }
488 }
489 ```
490
491 Ce changement a des conséquences sur la sécurité, puisque n\'importe quelle personne autorisée à interroger Varnish sera en mesure de récupérer un résultat en cache sans s\'identifier.
492
493 Il est important de valider la valeur de l\'en-tête Authorization avant de fournir le résultat depuis le cache.
494
495 Notre webservice a trois réponses possibles :
496 - 200: les données en JSON
497 - 404: données non trouvées
498 - 410: données plus jamais disponibles
499
500 Mettons en cache les résultats selon le code de retour :
501
502 ```varnish
503 sub vcl_fetch {
504 if (req.url ~ "^/webservice/uri/prefix/") {
505 if (beresp.status == 404) {
506 set beresp.ttl = 7d;
507 }
508 if (beresp.status == 410) {
509 set beresp.ttl = 7d;
510 }
511 if (beresp.status == 200) {
512 set beresp.ttl = 24h;
513 }
514 }
515 }
516 ```
517
518 Avec cette configuration, on a divisé par 5 la quantité de demandes sur notre passerelle pour le client qui n\'était pas en mesure de mettre en cache lui-même nos résultats.'
519 ]
520 ]
521 ],
522 [
523 'mail' => 'blog@rapsys.eu',
524 'keywords' => ['amazon', 'azure', 'cidr', 'microsoft', 'mysql', 'php', 'webservice'],
525 'translations' => [
526 'en_gb' => [
527 'title' => 'Dealing with IP range in PHP/MySQL',
528 'description' => 'I recently had to deal with CIDR blocks to tighten some webservice security.
529 Here is how I designed it to fulfill my needs.',
530 'body' => 'I recently had to deal with CIDR blocks to tighten some webservice security.
531
532 First let\'s see how to compute the first and last address of an IP range with just the block base IP and mask:
533
534 ```php
535 $range = [\'127.0.0.1\', 8];
536 function rangeBegin($range) {
537 return $range[0];
538 }
539 function rangeEnd($range) {
540 return long2ip(ip2long($range[0]) | ((1 << (32 - $range[1])) - 1));
541 }
542 ```
543
544 How to detect if an IP is present in a CIDR block:
545
546 ```php
547 $ip = \'127.0.0.1\';
548 $range = [\'127.0.0.1\', 8];
549 function ipInRange($ip, $range) {
550 if (ip2long($range[0]) <= ip2long($ip) && ip2long($ip) <= (ip2long($range[0]) | ((1 << (32 - $range[1])) - 1))) {
551 return true;
552 }
553 return false;
554 }
555 ```
556
557 As a first bonus, how to retrieve amazon IP ranges:
558
559 ```php
560 function fetchAmazonRange() {
561 //Init array
562 $amazonRanges = [];
563
564 $ctx = stream_context_create(
565 [
566 \'http\' => [
567 \'method\' => \'GET\',
568 \'max_redirects\' => 0,
569 \'timeout\' => 5,
570 \'ignore_errors\' => false,
571 \'header\' => [
572 \'Connection: close\',
573 \'Accept: application/json\'
574 ]
575 ]
576 ]
577 ];
578
579 //Fetch json
580 if (($json = file_get_contents(\'https://ip-ranges.amazonaws.com/ip-ranges.json\', false, $ctx)) === false) {
581 return null;
582 }
583
584 //Decode it
585 if (($json = json_decode($json)) === null || empty($json->prefixes)) {
586 return false;
587 }
588
589 //Deal with prefixes
590 foreach($json->prefixes as $range) {
591 //Skip ipv6 and invalid ranges
592 if (empty($range->ip_prefix)||!preg_match(\'/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+)$/\', $range->ip_prefix, $matche
593 s)) {
594 continue;
595 }
596 //Remove whole match
597 array_shift($matches);
598 //Add ip and mask
599 $amazonRanges[] = $matches;
600 }
601
602 //Send back result
603 return $amazonRanges;
604 }
605 ```
606
607 Microsoft Azure Ip ranges urls:
608 - <https://www.microsoft.com/en-us/download/details.aspx?id=41653>
609 - <https://msdn.microsoft.com/library/mt757330.aspx>'
610 ],
611 'fr_fr' => [
612 'title' => 'Gestion des plages d\'IP en PHP/MySQL',
613 'description' => 'J\'ai eu récemment à trouver comment restreindre l\'accès à un service en ligne à certaines plages d\'IP. Voici la solution qui a répondu à mes besoins.',
614 'body' => 'J\'ai récemment du autoriser l\'accès à un service en ligne à seulement quelques plages d\'IP.
615
616 Premièrement, voyons comment calculer la première et la dernière adresse IP d\'une plage (bloc CIDR) avec sa base et son masque :
617
618 ```php
619 $range = [\'127.0.0.1\', 8];
620 function rangeBegin($range) {
621 return $range[0];
622 }
623 function rangeEnd($range) {
624 return long2ip(ip2long($range[0]) | ((1 << (32 - $range[1])) - 1));
625 }
626 ```
627
628 Maintenant comment vérifier si une IP est présente dans une plage (bloc CIDR) :
629
630 ```php
631 $ip = \'127.0.0.1\';
632 $range = [\'127.0.0.1\', 8];
633 function ipInRange($ip, $range) {
634 if (ip2long($range[0]) <= ip2long($ip) && ip2long($ip) <= (ip2long($range[0]) | ((1 << (32 - $range[1])) - 1))) {
635 return true;
636 }
637 return false;
638 }
639 ```
640
641 En premier bonus, comment récupérer les plages d\'IP d\'amazon :
642
643 ```php
644 function fetchAmazonRange() {
645 //Init array
646 $amazonRanges = [];
647
648 $ctx = stream_context_create(
649 [
650 \'http\' => [
651 \'method\' => \'GET\',
652 \'max_redirects\' => 0,
653 \'timeout\' => 5,
654 \'ignore_errors\' => false,
655 \'header\' => [
656 \'Connection: close\',
657 \'Accept: application/json\'
658 ]
659 ]
660 ]
661 ];
662
663 //Fetch json
664 if (($json = file_get_contents(\'https://ip-ranges.amazonaws.com/ip-ranges.json\', false, $ctx)) === false) {
665 return null;
666 }
667
668 //Decode it
669 if (($json = json_decode($json)) === null || empty($json->prefixes)) {
670 return false;
671 }
672
673 //Deal with prefixes
674 foreach($json->prefixes as $range) {
675 //Skip ipv6 and invalid ranges
676 if (empty($range->ip_prefix)||!preg_match(\'/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+)$/\', $range->ip_prefix, $matche
677 s)) {
678 continue;
679 }
680 //Remove whole match
681 array_shift($matches);
682 //Add ip and mask
683 $amazonRanges[] = $matches;
684 }
685
686 //Send back result
687 return $amazonRanges;
688 }
689 ```
690
691 Urls pour les plages d\'IP de Microsoft Azure :
692 - <https://www.microsoft.com/en-us/download/details.aspx?id=41653>
693 - <https://msdn.microsoft.com/library/mt757330.aspx>'
694 ]
695 ]
696 ],
697 ];
698
699 //Create 3 articles
700 foreach($articleTree as $i => $data) {
701 $article = new Article($users[$data['mail']]);
702 foreach($data['keywords'] as $keyword) {
703 $article->addKeyword($keywords[$keyword]);
704 }
705 $manager->persist($article);
706 //Flush to get the id
707 $manager->flush();
708 $articles[$i] = $article;
709 foreach($data['translations'] as $locale => $translation) {
710 $articleTranslation = new ArticleTranslation($articles[$i], $locale, $translation['body'], $translation['description'], $this->slugger->slug($translation['title']), $translation['title']);
711 $manager->persist($articleTranslation);
712 }
713 unset($article);
714 }
715
716 //Flush to get the ids
717 $manager->flush();
718 }
719 }