repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
thecodeholic/Yii2-Youtube-Clone
https://github.com/thecodeholic/Yii2-Youtube-Clone/blob/d8d6c35890b5d3ebb00b0cc6ace20deea99974b1/environments/prod/frontend/config/params-local.php
environments/prod/frontend/config/params-local.php
<?php return [ ];
php
BSD-3-Clause
d8d6c35890b5d3ebb00b0cc6ace20deea99974b1
2026-01-05T04:42:11.286050Z
false
thecodeholic/Yii2-Youtube-Clone
https://github.com/thecodeholic/Yii2-Youtube-Clone/blob/d8d6c35890b5d3ebb00b0cc6ace20deea99974b1/environments/prod/frontend/config/main-local.php
environments/prod/frontend/config/main-local.php
<?php return [ 'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation 'cookieValidationKey' => '', ], ], ];
php
BSD-3-Clause
d8d6c35890b5d3ebb00b0cc6ace20deea99974b1
2026-01-05T04:42:11.286050Z
false
thecodeholic/Yii2-Youtube-Clone
https://github.com/thecodeholic/Yii2-Youtube-Clone/blob/d8d6c35890b5d3ebb00b0cc6ace20deea99974b1/environments/prod/frontend/web/index.php
environments/prod/frontend/web/index.php
<?php defined('YII_DEBUG') or define('YII_DEBUG', false); defined('YII_ENV') or define('YII_ENV', 'prod'); require __DIR__ . '/../../vendor/autoload.php'; require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php'; require __DIR__ . '/../../common/config/bootstrap.php'; require __DIR__ . '/../config/bootstrap.php'; $config = yii\helpers\ArrayHelper::merge( require __DIR__ . '/../../common/config/main.php', require __DIR__ . '/../../common/config/main-local.php', require __DIR__ . '/../config/main.php', require __DIR__ . '/../config/main-local.php' ); (new yii\web\Application($config))->run();
php
BSD-3-Clause
d8d6c35890b5d3ebb00b0cc6ace20deea99974b1
2026-01-05T04:42:11.286050Z
false
nmcteam/image-with-text
https://github.com/nmcteam/image-with-text/blob/51f6442d8d80278ddca5462f766de4477812aaf4/src/NMC/ImageWithText/Text.php
src/NMC/ImageWithText/Text.php
<?php /** * Image with Text * * @author Josh Lockhart <josh@newmediacampaigns.com> * @copyright 2013 Josh Lockhart * @link https://github.com/nmcteam/image-with-text * @license MIT * @version 2.0.2 * * MIT LICENSE * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace NMC\ImageWithText; /** * Text * * This class represents a single text block that will be drawn onto * an image. You may control this text block's: * * - alignment * - color * - font * - line height * - size * * You can also position this text block using specific X and Y coordinates relative * to its source image. * * Currently this has a hard dependency on the `\Intervention\Image` class and the * GD2 image library. We will be abstracting away these dependencies soon. * * @author Josh Lockhart * @since 2.0.0 */ class Text { /** * Text * @var string * @api */ public $text = 'Hello world'; /** * Width (max number of characters per line) * @var int */ public $width = 80; /** * X coordinate offset from which text will be positioned relative to source image * @var int * @api */ public $startX = 0; /** * Y coordinate offset from which text will be positioned relative to source image * @var int * @api */ public $startY = 0; /** * Text alignment (one of "left", "center", or "right") * @var string * @api */ public $align = 'left'; /** * Text color (Hexadecimal, without "#" prefix... "000000") * @var string * @api */ public $color = '000000'; /** * Text font (path to TTF or OTF file) * @var string * @api */ public $font = 'arial.ttf'; /** * Text line height (measured in pts) * @var int * @api */ public $lineHeight = 24; /** * Text size (measured in pts) * @var int * @api */ public $size = 16; /** * Array of available lines, with character counts and allocated words * @var array */ protected $lines; /** * Construct * @param string $text The text * @param int $numLines The total number of available lines * @param int $width The maximum number of characters avaiable per line */ public function __construct($text, $numLines = 1, $width = 80) { $this->text = $text; $this->width = $width; $this->addLines($numLines); } /** * Add available lines of text * @param int $numLines The number of available lines to add * @api */ public function addLines($numLines = 1) { for ($i = 0; $i < $numLines; $i++) { $this->lines[] = array( 'chars' => 0, 'words' => array(), 'full' => false ); } } /** * Render text on image * @param \Intervention\Image\Image $image The image on which the text will be rendered * @api */ public function renderToImage(\NMC\ImageWithText\Image $image) { // Allocate words to lines $this->distributeText(); // Calculate maximum potential line width (close enough) in pixels $maxWidthString = implode('', array_fill(0, $this->width, 'x')); $maxWidthBoundingBox = imagettfbbox($this->size, 0, $this->font, $maxWidthString); $maxLineWidth = abs($maxWidthBoundingBox[0] - $maxWidthBoundingBox[2]); // (lower left corner, X position) - (lower right corner, X position) // Calculate each line width in pixels for alignment purposes for ($j = 0; $j < count($this->lines); $j++) { // Fetch line $line =& $this->lines[$j]; // Remove unused lines if (empty($line['words'])) { unset($this->lines[$j]); continue; } // Calculate width $lineText = implode(' ', $line['words']); $lineBoundingBox = imagettfbbox($this->size, 0, $this->font, $lineText); $line['width'] = abs($lineBoundingBox[0] - $lineBoundingBox[2]); // (lower left corner, X position) - (lower right corner, X position) $line['text'] = $lineText; } // Calculate line offsets for ($i = 0; $i < count($this->lines); $i++) { // Fetch line if (array_key_exists($i, $this->lines)) { $line =& $this->lines[$i]; // Calculate line width in pixels $lineBoundingBox = imagettfbbox($this->size, 0, $this->font, $line['text']); $lineWidth = abs($lineBoundingBox[0] - $lineBoundingBox[2]); // (lower left corner, X position) - (lower right corner, X position) // Calculate line X,Y offsets in pixels switch ($this->align) { case 'left': $offsetX = $this->startX; $offsetY = $this->startY + $this->lineHeight + ($this->lineHeight * $i); break; case 'center': $imageWidth = $image->getWidth(); $offsetX = (($maxLineWidth - $lineWidth) / 2) + $this->startX; $offsetY = $this->startY + $this->lineHeight + ($this->lineHeight * $i); break; case 'right': $imageWidth = $image->getWidth(); $offsetX = $imageWidth - $line['width'] - $this->startX; $offsetY = $this->startY + $this->lineHeight + ($this->lineHeight * $i); break; } // Render text onto image $image->getImage()->text($line['text'], $offsetX, $offsetY, $this->size, $this->color, 0, $this->font); } } } /** * Distribute text to lines * @throws \Exception If text is too long given available lines and max character width */ protected function distributeText() { // Explode input text on word boundaries $words = explode(' ', $this->text); // Fill lines with words, toss exception if exceed available lines while ($words) { $tooLong = true; $word = array_shift($words); for ($i = 0; $i < count($this->lines); $i++) { $line =& $this->lines[$i]; if ($line['full'] === false) { $charsPotential = strlen($word) + $line['chars']; if ($charsPotential <= $this->width) { array_push($line['words'], $word); $line['chars'] = $charsPotential; $tooLong = false; break; } else { $line['full'] = true; } } } } // Throw if too long if ($tooLong === true) { throw new \Exception('Text is too long'); } } }
php
MIT
51f6442d8d80278ddca5462f766de4477812aaf4
2026-01-05T04:42:19.903079Z
false
nmcteam/image-with-text
https://github.com/nmcteam/image-with-text/blob/51f6442d8d80278ddca5462f766de4477812aaf4/src/NMC/ImageWithText/Image.php
src/NMC/ImageWithText/Image.php
<?php /** * Image with Text * * @author Josh Lockhart <josh@newmediacampaigns.com> * @copyright 2013 Josh Lockhart * @link https://github.com/nmcteam/image-with-text * @license MIT * @version 2.0.2 * * MIT LICENSE * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace NMC\ImageWithText; /** * Image * * This class makes it super easy to render an image with multiple, independently * styled and positioned text blocks. You can control these properties for each text block: * * - alignment * - color * - font * - line height * - size * * You can also position each text block using specific X and Y coordinates relative * to the source image. * * Currently this has a hard dependency on the `\Intervention\Image` class and the * GD2 image library. We will be abstracting away these dependencies soon. * * @author Josh Lockhart * @since 1.0.0 */ class Image { /** * Image * @var \Intervention\Image\Image * @api */ public $image; /** * Text objects * @var array[\NMC\ImageWithText\Text] */ public $textObjects = array(); /** * Construct from image with text * @param string $sourceImage Path to source image * @api */ public function __construct($sourceImage) { $this->image = \Intervention\Image\Image::make($sourceImage); } /** * Add text * @param \NMC\ImageWithText\Text $text */ public function addText(\NMC\ImageWithText\Text $text) { $this->textObjects[] = $text; } /** * Draw text onto image * @api */ public function drawText() { foreach ($this->textObjects as $text) { $text->renderToImage($this); } } /** * Save rendered image to output file * @param string $outputImagePath The path to which the image (with text) will be saved * @api */ public function render($outputImagePath) { $this->drawText(); $this->image->save($outputImagePath); } /** * Get image width * @return int */ public function getWidth() { return imagesx($this->image->resource); } /** * Get image * @return \Intervention\Image\Image */ public function getImage() { return $this->image; } }
php
MIT
51f6442d8d80278ddca5462f766de4477812aaf4
2026-01-05T04:42:19.903079Z
false
nmcteam/image-with-text
https://github.com/nmcteam/image-with-text/blob/51f6442d8d80278ddca5462f766de4477812aaf4/example/demo.php
example/demo.php
<?php require '../vendor/autoload.php'; // Create image $image = new \NMC\ImageWithText\Image(dirname(__FILE__) . '/source.jpg'); // Add styled text to image $text1 = new \NMC\ImageWithText\Text('Thanks for using our image text PHP library!', 3, 25); $text1->align = 'left'; $text1->color = 'FFFFFF'; $text1->font = dirname(__FILE__) . '/Ubuntu-Medium.ttf'; $text1->lineHeight = 36; $text1->size = 24; $text1->startX = 40; $text1->startY = 40; $image->addText($text1); // Add another styled text to image $text2 = new \NMC\ImageWithText\Text('No, really, thanks!', 1, 30); $text2->align = 'left'; $text2->color = '000000'; $text2->font = dirname(__FILE__) . '/Ubuntu-Medium.ttf'; $text2->lineHeight = 20; $text2->size = 14; $text2->startX = 40; $text2->startY = 140; $image->addText($text2); // Render image $image->render(dirname(__FILE__) . '/destination.jpg');
php
MIT
51f6442d8d80278ddca5462f766de4477812aaf4
2026-01-05T04:42:19.903079Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/HaltCommand.php
src/HaltCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Process\Process; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class HaltCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this->setName('halt')->setDescription('Halt the Homestead machine'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $process = new Process('vagrant halt', realpath(__DIR__.'/../'), array_merge($_SERVER, $_ENV), null, null); $process->run(function ($type, $line) use ($output) { $output->write($line); }); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/ResumeCommand.php
src/ResumeCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Process\Process; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ResumeCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this->setName('resume')->setDescription('Resume the suspended Homestead machine'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $process = new Process('vagrant resume', realpath(__DIR__.'/../'), array_merge($_SERVER, $_ENV), null, null); $process->run(function ($type, $line) use ($output) { $output->write($line); }); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/DestroyCommand.php
src/DestroyCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Process\Process; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class DestroyCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this->setName('destroy')->setDescription('Destroy the Homestead machine'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $process = new Process('vagrant destroy --force', realpath(__DIR__.'/../'), array_merge($_SERVER, $_ENV), null, null); $process->run(function ($type, $line) use ($output) { $output->write($line); }); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/MakeCommand.php
src/MakeCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class MakeCommand extends Command { /** * The base path of the Laravel installation. * * @var string */ protected $basePath; /** * The name of the project folder. * * @var string */ protected $projectName; /** * Sluggified Project Name. * * @var string */ protected $defaultName; /** * Configure the command options. * * @return void */ protected function configure() { $this->basePath = getcwd(); $this->projectName = basename(getcwd()); $this->defaultName = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $this->projectName))); $this ->setName('make') ->setDescription('Install Homestead into the current project') ->addOption('name', null, InputOption::VALUE_OPTIONAL, 'The name the virtual machine.', $this->defaultName) ->addOption('hostname', null, InputOption::VALUE_OPTIONAL, 'The hostname the virtual machine.', $this->defaultName) ->addOption('after', null, InputOption::VALUE_NONE, 'Determines if the after.sh file is created.') ->addOption('aliases', null, InputOption::VALUE_NONE, 'Determines if the aliases file is created.'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { copy(__DIR__.'/stubs/LocalizedVagrantfile', $this->basePath.'/Vagrantfile'); if (! file_exists($this->basePath.'/Homestead.yaml')) { copy(__DIR__.'/stubs/Homestead.yaml', $this->basePath.'/Homestead.yaml'); if ($input->getOption('name')) { $this->updateName($input->getOption('name')); } if ($input->getOption('hostname')) { $this->updateHostName($input->getOption('hostname')); } } if ($input->getOption('after')) { if (! file_exists($this->basePath.'/after.sh')) { copy(__DIR__.'/stubs/after.sh', $this->basePath.'/after.sh'); } } if ($input->getOption('aliases')) { if (! file_exists($this->basePath.'/aliases')) { copy(__DIR__.'/stubs/aliases', $this->basePath.'/aliases'); } } $this->configurePaths(); $output->writeln('Homestead Installed!'); } /** * Update paths in Homestead.yaml. * * @return void */ protected function configurePaths() { $yaml = str_replace( '- map: ~/Code', '- map: "'.str_replace('\\', '/', $this->basePath).'"', $this->getHomesteadFile() ); $yaml = str_replace( 'to: /home/vagrant/Code', 'to: "/home/vagrant/'.$this->defaultName.'"', $yaml ); // Fix path to the public folder (sites: to:) $yaml = str_replace( $this->defaultName.'"/Laravel/public', $this->defaultName.'/public"', $yaml ); file_put_contents($this->basePath.'/Homestead.yaml', $yaml); } /** * Update the "name" variable of the Homestead.yaml file. * * VirtualBox requires a unique name for each virtual machine. * * @param string $name * @return void */ protected function updateName($name) { file_put_contents($this->basePath.'/Homestead.yaml', str_replace( 'cpus: 1', 'cpus: 1'.PHP_EOL.'name: '.$name, $this->getHomesteadFile() )); } /** * Set the virtual machine's hostname setting in the Homestead.yaml file. * * @param string $hostname * @return void */ protected function updateHostName($hostname) { file_put_contents($this->basePath.'/Homestead.yaml', str_replace( 'cpus: 1', 'cpus: 1'.PHP_EOL.'hostname: '.$hostname, $this->getHomesteadFile() )); } /** * Get the contents of the Homestead.yaml file. * * @return string */ protected function getHomesteadFile() { return file_get_contents($this->basePath.'/Homestead.yaml'); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/StatusCommand.php
src/StatusCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Process\Process; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class StatusCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this->setName('status')->setDescription('Get the status of the Homestead machine'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $process = new Process('vagrant status', realpath(__DIR__.'/../'), array_merge($_SERVER, $_ENV), null, null); $process->run(function ($type, $line) use ($output) { $output->write($line); }); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/EditCommand.php
src/EditCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Process\Process; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class EditCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this ->setName('edit') ->setDescription('Edit a Homestead file') ->addArgument('file', InputArgument::OPTIONAL, 'The file you wish to edit.'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $file = 'Homestead.yaml'; if ($input->getArgument('file') === 'aliases') { $file = 'aliases'; } $command = $this->executable().' '.homestead_path().'/'.$file; $process = new Process($command, realpath(__DIR__.'/../'), array_merge($_SERVER, $_ENV), null, null); $process->run(function ($type, $line) use ($output) { $output->write($line); }); } /** * Find the correct executable to run depending on the OS. * * @return string */ protected function executable() { if (strpos(strtoupper(PHP_OS), 'WIN') === 0) { return 'start'; } elseif (strpos(strtoupper(PHP_OS), 'DARWIN') === 0) { return 'open'; } return 'xdg-open'; } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/ProvisionCommand.php
src/ProvisionCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Process\Process; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ProvisionCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this->setName('provision')->setDescription('Re-provisions the Homestead machine'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $process = new Process('vagrant provision', realpath(__DIR__.'/../'), array_merge($_SERVER, $_ENV), null, null); $process->run(function ($type, $line) use ($output) { $output->write($line); }); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/UpCommand.php
src/UpCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Process\Process; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class UpCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this ->setName('up') ->setDescription('Start the Homestead machine') ->addOption('provision', null, InputOption::VALUE_NONE, 'Run the provisioners on the box.'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $command = 'vagrant up'; if ($input->getOption('provision')) { $command .= ' --provision'; } $process = new Process($command, realpath(__DIR__.'/../'), array_merge($_SERVER, $_ENV), null, null); $process->run(function ($type, $line) use ($output) { $output->write($line); }); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/SuspendCommand.php
src/SuspendCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Process\Process; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class SuspendCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this->setName('suspend')->setDescription('Suspend the Homestead machine'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $process = new Process('vagrant suspend', realpath(__DIR__.'/../'), array_merge($_SERVER, $_ENV), null, null); $process->run(function ($type, $line) use ($output) { $output->write($line); }); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/SshCommand.php
src/SshCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class SshCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this->setName('ssh')->setDescription('Login to the Homestead machine via SSH'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { chdir(__DIR__.'/../'); passthru($this->setEnvironmentCommand().' vagrant ssh'); } protected function setEnvironmentCommand() { if ($this->isWindows()) { return 'SET VAGRANT_DOTFILE_PATH='.$_ENV['VAGRANT_DOTFILE_PATH'].' &&'; } return 'VAGRANT_DOTFILE_PATH="'.$_ENV['VAGRANT_DOTFILE_PATH'].'"'; } protected function isWindows() { return strpos(strtoupper(PHP_OS), 'WIN') === 0; } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/AddSiteCommand.php
src/AddSiteCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Yaml\Yaml; class AddSiteCommand extends Command { /** * @var array */ private $homesteadYamlContents; /** * @var OutputInterface */ private $output; /** * Configure the command options. * * @return void */ protected function configure() { $this ->setName('add-site') ->setDescription('Add a new site to the Homestead.yaml file') ->addArgument('hostname', InputArgument::REQUIRED, 'the hostname to add') ->addArgument('path', InputArgument::REQUIRED, 'the path for the given hostname'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $this->homesteadYamlContents = Yaml::parse(file_get_contents('./Homestead.yaml')); $this->output = $output; $hostname = $input->getArgument('hostname'); $path = $input->getArgument('path'); $canAddItem = $this->canItemBeAdded($hostname, $path); if($canAddItem) { $this->addItemAndSaveToYamlFile($hostname, $path); } } /** * @param $currentSites * @param $hostname * @param $path * @param OutputInterface $output * * @return bool */ private function canItemBeAdded($hostname, $path) { $canAddItem = true; foreach($this->homesteadYamlContents['sites'] as $site) { if($site['map'] === $hostname) { $this->output->writeln(sprintf('<error>Hostname %s already used.</error>', $hostname)); $canAddItem = false; break; } if($site['to'] === $path) { $this->output->writeln(sprintf('<error>Path %s already mapped to %s</error>', $path, $site['to'])); $canAddItem = false; break; } } return $canAddItem; } private function addItemAndSaveToYamlFile($hostname, $path) { $this->homesteadYamlContents['sites'][] = [ 'map' => $hostname, 'to' => $path ]; file_put_contents('./Homestead.yaml', Yaml::dump($this->homesteadYamlContents)); $this->output->writeln('<info>New site successfully added.</info>'); $this->output->write('<info>Don\'t forget to re-provision your VM.</info>'); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/SshConfigCommand.php
src/SshConfigCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class SshConfigCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this->setName('ssh-config')->setDescription('Outputs OpenSSH valid configuration to connect to Homestead'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { chdir(__DIR__.'/../'); passthru($this->setDotFileInEnvironment().' vagrant ssh-config'); } /** * Set the dot file path in the environment. * * @return void */ protected function setDotFileInEnvironment() { if ($this->isWindows()) { return 'SET VAGRANT_DOTFILE_PATH='.$_ENV['VAGRANT_DOTFILE_PATH'].' &&'; } return 'VAGRANT_DOTFILE_PATH="'.$_ENV['VAGRANT_DOTFILE_PATH'].'"'; } /** * Determine if the machine is running the Windows operating system. * * @return bool */ protected function isWindows() { return strpos(strtoupper(PHP_OS), 'WIN') === 0; } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/AddDatabaseCommand.php
src/AddDatabaseCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Yaml\Yaml; class AddDatabaseCommand extends Command { /** * @var array */ private $homesteadYamlContents; /** * @var OutputInterface */ private $output; /** * Configure the command options. * * @return void */ protected function configure() { $this ->setName('add-db') ->setDescription('Add a new database to the Homestead.yaml file') ->addArgument('name', InputArgument::REQUIRED, 'the database name to be added'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $this->homesteadYamlContents = Yaml::parse(file_get_contents('./Homestead.yaml')); $this->output = $output; $name = $input->getArgument('name'); $canAddItem = $this->canItemBeAdded($name); if($canAddItem) { $this->addItemAndSaveToYamlFile($name); } } /** * @param $name * * @return bool */ private function canItemBeAdded($name) { $canAddItem = true; foreach($this->homesteadYamlContents['databases'] as $database) { if($database === $name) { $this->output->writeln(sprintf('<error>Database %s already defined.</error>', $name)); $canAddItem = false; break; } } return $canAddItem; } /** * @param $name */ private function addItemAndSaveToYamlFile($name) { $this->homesteadYamlContents['databases'][] = $name; file_put_contents('./Homestead.yaml', Yaml::dump($this->homesteadYamlContents)); $this->output->writeln('<info>New database successfully added.</info>'); $this->output->write('<info>Don\'t forget to re-provision your VM.</info>'); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/UpdateCommand.php
src/UpdateCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Process\Process; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class UpdateCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this->setName('update')->setDescription('Update the Homestead machine image'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $process = new Process('vagrant box update', realpath(__DIR__.'/../'), array_merge($_SERVER, $_ENV), null, null); $process->run(function ($type, $line) use ($output) { $output->write($line); }); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/RunCommand.php
src/RunCommand.php
<?php namespace Laravel\Homestead; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class RunCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this ->setName('run') ->setDescription('Run commands through the Homestead machine via SSH') ->addArgument('ssh-command', InputArgument::REQUIRED, 'The command to pass through to the virtual machine.'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { chdir(__DIR__.'/../'); $command = $input->getArgument('ssh-command'); passthru($this->setEnvironmentCommand().' vagrant ssh -c "'.$command.'"'); } protected function setEnvironmentCommand() { if ($this->isWindows()) { return 'SET VAGRANT_DOTFILE_PATH='.$_ENV['VAGRANT_DOTFILE_PATH'].' &&'; } return 'VAGRANT_DOTFILE_PATH="'.$_ENV['VAGRANT_DOTFILE_PATH'].'"'; } protected function isWindows() { return strpos(strtoupper(PHP_OS), 'WIN') === 0; } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
Swader/homestead_improved
https://github.com/Swader/homestead_improved/blob/efa9968eb4f6fddca1611841867a1cc083c8ac59/src/InitCommand.php
src/InitCommand.php
<?php namespace Laravel\Homestead; use InvalidArgumentException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class InitCommand extends Command { /** * Configure the command options. * * @return void */ protected function configure() { $this->setName('init')->setDescription('Create a stub Homestead.yaml file'); } /** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { if (is_dir(homestead_path())) { throw new InvalidArgumentException('Homestead has already been initialized.'); } mkdir(homestead_path()); copy(__DIR__.'/stubs/Homestead.yaml', homestead_path().'/Homestead.yaml'); copy(__DIR__.'/stubs/after.sh', homestead_path().'/after.sh'); copy(__DIR__.'/stubs/aliases', homestead_path().'/aliases'); $output->writeln('<comment>Creating Homestead.yaml file...</comment> <info>✔</info>'); $output->writeln('<comment>Homestead.yaml file created at:</comment> '.homestead_path().'/Homestead.yaml'); } }
php
MIT
efa9968eb4f6fddca1611841867a1cc083c8ac59
2026-01-05T04:42:23.201809Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/src/ClickhouseServiceProvider.php
src/ClickhouseServiceProvider.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Laravel\Clickhouse; use ClickHouseDB\Client as ClickhouseClient; use Cog\Laravel\Clickhouse\ConsoleCommand\ClickhouseMigrateCommand; use Cog\Laravel\Clickhouse\ConsoleCommand\MakeClickhouseMigrationCommand; use Cog\Laravel\Clickhouse\Factory\ClickhouseClientFactory; use Cog\Laravel\Clickhouse\Migration\MigrationCreator; use Cog\Laravel\Clickhouse\Migration\MigrationRepository; use Cog\Laravel\Clickhouse\Migration\Migrator; use Illuminate\Contracts\Config\Repository as AppConfigRepositoryInterface; use Illuminate\Filesystem\Filesystem; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; final class ClickhouseServiceProvider extends ServiceProvider { private const CONFIG_FILE_PATH = __DIR__ . '/../config/clickhouse.php'; public function register(): void { $this->app->singleton( ClickhouseClient::class, static function (Application $app): ClickhouseClient { $appConfigRepository = $app->get(AppConfigRepositoryInterface::class); $connectionConfig = $appConfigRepository->get('clickhouse.connection', []); $clickhouseClientFactory = new ClickhouseClientFactory($connectionConfig); return $clickhouseClientFactory->create(); }, ); $this->app->singleton( Migrator::class, static function (Application $app): Migrator { $client = $app->get(ClickhouseClient::class); $filesystem = $app->get(Filesystem::class); $appConfigRepository = $app->get(AppConfigRepositoryInterface::class); $table = $appConfigRepository->get('clickhouse.migrations.table'); $repository = new MigrationRepository( $client, $table, ); return new Migrator( $client, $repository, $filesystem, ); }, ); $this->app->singleton( MigrationCreator::class, static function (Application $app): MigrationCreator { return new MigrationCreator( $app->get(Filesystem::class), $app->basePath('stubs'), ); }, ); } public function boot(): void { $this->configure(); $this->registerConsoleCommands(); $this->registerPublishes(); } private function configure(): void { if (!$this->app->configurationIsCached()) { $this->mergeConfigFrom( self::CONFIG_FILE_PATH, 'clickhouse', ); } } private function registerConsoleCommands(): void { if ($this->app->runningInConsole()) { $this->commands( [ ClickhouseMigrateCommand::class, MakeClickhouseMigrationCommand::class, ], ); } } private function registerPublishes(): void { if ($this->app->runningInConsole()) { $this->publishes( [ self::CONFIG_FILE_PATH => $this->app->configPath('clickhouse.php'), ], 'config', ); } } }
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/src/Migration/MigrationCreator.php
src/Migration/MigrationCreator.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Laravel\Clickhouse\Migration; use Illuminate\Filesystem\Filesystem; class MigrationCreator { public function __construct( private Filesystem $filesystem, private ?string $migrationStubFilePath, ) {} public function create( string $fileName, string $migrationsDirectoryPath, ): ?string { $stubFileContent = $this->getStubFileContent(); $filePath = $this->generateMigrationFilePath($fileName, $migrationsDirectoryPath); $this->filesystem->ensureDirectoryExists(dirname($filePath)); $this->filesystem->put($filePath, $stubFileContent); return $filePath; } private function generateMigrationFilePath( string $name, string $migrationsDirectoryPath, ): string { return $migrationsDirectoryPath . '/' . $this->getDatePrefix() . '_' . $name . '.php'; } /** * Get the date prefix for the migration. */ protected function getDatePrefix(): string { return date('Y_m_d_His'); } protected function getStubFileContent(): string { $stubFileName = 'clickhouse-migration.stub'; $customStubFilePath = $this->migrationStubFilePath . '/' . $stubFileName; $stub = $this->filesystem->exists($customStubFilePath) ? $customStubFilePath : $this->getDefaultStubFilePath() . '/' . $stubFileName; return $this->filesystem->get($stub); } public function getDefaultStubFilePath(): string { return __DIR__ . '/../../stubs'; } }
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/src/Migration/MigrationRepository.php
src/Migration/MigrationRepository.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Laravel\Clickhouse\Migration; use ClickHouseDB\Client; use ClickHouseDB\Statement; final class MigrationRepository { public function __construct( private Client $client, private string $table, ) {} /** * Creating a new table to store migrations. */ public function createMigrationRegistryTable(): Statement { return $this->client->write( <<<SQL CREATE TABLE IF NOT EXISTS {table} ( migration String, batch UInt32, applied_at DateTime DEFAULT NOW() ) ENGINE = ReplacingMergeTree() ORDER BY migration SQL, [ 'table' => $this->table, ], ); } /** * @return array */ public function all(): array { $rows = $this->client->select( <<<SQL SELECT migration FROM {table} SQL, [ 'table' => $this->table, ], )->rows(); return collect($rows)->pluck('migration')->all(); } /** * Get latest accepted migrations. * * @return array */ public function latest(): array { $rows = $this->client->select( <<<SQL SELECT migration FROM {table} ORDER BY batch DESC, migration DESC SQL, [ 'table' => $this->table, ], )->rows(); return collect($rows)->pluck('migration')->all(); } public function getNextBatchNumber(): int { return $this->getLastBatchNumber() + 1; } public function getLastBatchNumber(): int { return $this->client ->select( <<<SQL SELECT MAX(batch) AS batch FROM {table} SQL, [ 'table' => $this->table, ], ) ->fetchOne('batch'); } public function add( string $migration, int $batch, ): Statement { return $this->client->insert( $this->table, [[$migration, $batch]], ['migration', 'batch'], ); } public function total(): int { return (int)$this->client->select( <<<SQL SELECT COUNT(*) AS count FROM {table} SQL, [ 'table' => $this->table, ], )->fetchOne('count'); } public function exists(): bool { return (bool)$this->client->select( <<<SQL EXISTS TABLE {table} SQL, [ 'table' => $this->table, ], )->fetchOne('result'); } /** * @param string $migration * @return array|null */ public function find( string $migration, ): ?array { return $this->client->select( <<<SQL SELECT * FROM {table} WHERE migration = :migration LIMIT 1 SQL, [ 'table' => $this->table, 'migration' => $migration, ], )->fetchOne(); } }
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/src/Migration/Migrator.php
src/Migration/Migrator.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Laravel\Clickhouse\Migration; use ClickHouseDB\Client; use DomainException; use Generator; use Illuminate\Console\OutputStyle; use Illuminate\Contracts\Filesystem\FileNotFoundException; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Str; use ReflectionClass; use Symfony\Component\Finder\SplFileInfo; use function in_array; final class Migrator { public function __construct( private Client $client, private MigrationRepository $repository, private Filesystem $filesystem, ) {} /** * @throws FileNotFoundException */ public function runUp( string $migrationsDirectoryPath, OutputStyle $output, int $step, ): void { $migrations = $this->getMigrationsUp($migrationsDirectoryPath); if ($migrations->valid() === false) { $output->writeln( '<info>Migrations are empty.</info>', ); return; } $nextBatch = $this->repository->getNextBatchNumber(); for ($i = $step; ($i > 0 || $step === 0) && $migrations->valid(); $i--) { $this->filesystem->requireOnce($migrations->current()); $startTime = microtime(true); $migration = $this->resolveMigrationInstance($migrations->current()); $migration->up(); $runTime = round(microtime(true) - $startTime, 2); $migrationName = $this->resolveMigrationNameFromInstance($migration); $this->repository->add($migrationName, $nextBatch); $output->writeln( "<info>Completed in {$runTime} seconds</info> {$migrationName}", ); $migrations->next(); } } public function ensureTableExists(): self { if ($this->repository->exists() === false) { $this->repository->createMigrationRegistryTable(); } return $this; } private function getMigrationsUp( string $migrationsDirectoryPath, ): Generator { $migrationFiles = $this->getUnAppliedMigrationFiles($migrationsDirectoryPath); foreach ($migrationFiles as $migrationFile) { yield $migrationsDirectoryPath . '/' . $migrationFile->getFilename(); } } private function getMigrationName( string $migrationFilePath, ): string { return str_replace('.php', '', basename($migrationFilePath)); } /** * @return list<SplFileInfo> */ private function getUnAppliedMigrationFiles( string $migrationsDirectoryPath, ): array { $migrationFiles = $this->filesystem->files($migrationsDirectoryPath); return collect($migrationFiles) ->reject( fn(SplFileInfo $migrationFile) => $this->isAppliedMigration($migrationFile->getFilename()), )->all(); } /** * @throws FileNotFoundException */ private function resolveMigrationInstance( string $path, ): object { $class = $this->generateMigrationClassName($this->getMigrationName($path)); if (class_exists($class) && realpath($path) === (new ReflectionClass($class))->getFileName()) { return new $class($this->client); } $migration = $this->filesystem->getRequire($path); return is_object($migration) ? $migration : new $class($this->client); } private function generateMigrationClassName( string $migrationName, ): string { return Str::studly( implode('_', array_slice(explode('_', $migrationName), 4)), ); } private function resolveMigrationNameFromInstance( object $migration, ): string { $reflectionClass = new ReflectionClass($migration); if ($reflectionClass->isAnonymous() === false) { throw new DomainException('Only anonymous migrations are supported'); } return $this->getMigrationName($reflectionClass->getFileName()); } private function isAppliedMigration( string $fileName, ): bool { return in_array( $this->getMigrationName($fileName), $this->repository->all(), true, ); } }
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/src/Migration/AbstractClickhouseMigration.php
src/Migration/AbstractClickhouseMigration.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Laravel\Clickhouse\Migration; use ClickHouseDB\Client; use function config; abstract class AbstractClickhouseMigration { protected Client $clickhouseClient; protected string $databaseName; public function __construct( ?Client $clickhouseClient = null, ?string $databaseName = null, ) { $this->clickhouseClient = $clickhouseClient ?? app(Client::class); $this->databaseName = $databaseName ?? config('clickhouse.connection.options.database'); } public function getClickhouseClient(): Client { return $this->clickhouseClient; } public function getDatabaseName(): string { return $this->databaseName; } }
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/src/Exception/ClickhouseConfigException.php
src/Exception/ClickhouseConfigException.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Laravel\Clickhouse\Exception; use Exception; final class ClickhouseConfigException extends Exception {}
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/src/ConsoleCommand/MakeClickhouseMigrationCommand.php
src/ConsoleCommand/MakeClickhouseMigrationCommand.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Laravel\Clickhouse\ConsoleCommand; use Cog\Laravel\Clickhouse\Migration\MigrationCreator; use Illuminate\Console\Command; use Illuminate\Contracts\Config\Repository as AppConfigRepositoryInterface; use Illuminate\Contracts\Filesystem\FileNotFoundException; use Illuminate\Support\Composer; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; #[AsCommand( name: 'make:clickhouse-migration', description: 'Create a new ClickHouse migration file', )] final class MakeClickhouseMigrationCommand extends Command { protected function getArguments(): array { return [ new InputArgument( 'name', InputArgument::REQUIRED, 'The name of the migration', ), ]; } protected function getOptions(): array { return [ new InputOption( 'path', null, InputOption::VALUE_REQUIRED, 'The location where the migration file should be created', ), new InputOption( 'realpath', null, InputOption::VALUE_NONE, 'Indicate any provided migration file paths are pre-resolved absolute paths', ), new InputOption( 'fullpath', null, InputOption::VALUE_NONE, 'Output the full path of the migration', ), ]; } public function __construct( private MigrationCreator $migrationCreator, private Composer $composer, private AppConfigRepositoryInterface $appConfigRepository, ) { parent::__construct(); } /** * @throws FileNotFoundException */ public function handle(): int { $migrationFileName = $this->getNameArgument(); $this->writeMigration($migrationFileName); $this->composer->dumpAutoloads(); return self::SUCCESS; } /** * @throws FileNotFoundException */ private function writeMigration( string $migrationFileName, ): void { $filePath = $this->migrationCreator->create( $migrationFileName, $this->getMigrationPath(), ); if (!$this->option('fullpath')) { $filePath = pathinfo($filePath, PATHINFO_FILENAME); } $this->line("<info>Created Migration:</info> $filePath"); } protected function getNameArgument(): string { return trim($this->argument('name')); } /** * Get migration path (either specified by '--path' option or default location). */ private function getMigrationPath(): string { $targetPath = $this->input->getOption('path'); if ($targetPath !== null) { return $this->isUsingRealPath() ? $targetPath : $this->laravel->basePath() . '/' . $targetPath; } return rtrim( $this->appConfigRepository->get('clickhouse.migrations.path'), '/', ); } /** * Determine if the given path(s) are pre-resolved "real" paths. */ protected function isUsingRealPath(): bool { return $this->input->hasOption('realpath') && $this->option('realpath'); } }
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/src/ConsoleCommand/ClickhouseMigrateCommand.php
src/ConsoleCommand/ClickhouseMigrateCommand.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Laravel\Clickhouse\ConsoleCommand; use Cog\Laravel\Clickhouse\Migration\Migrator; use Illuminate\Console\Command; use Illuminate\Console\ConfirmableTrait; use Illuminate\Contracts\Config\Repository as AppConfigRepositoryInterface; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand( name: 'clickhouse:migrate', description: 'Run the ClickHouse database migrations', )] final class ClickhouseMigrateCommand extends Command { use ConfirmableTrait; /** * {@inheritdoc} */ protected $signature = 'clickhouse:migrate {--force : Force the operation to run when in production} {--path= : Path to Clickhouse directory with migrations} {--realpath : Indicate any provided migration file paths are pre-resolved absolute paths} {--step= : Number of migrations to run}'; public function __construct( private Migrator $migrator, private AppConfigRepositoryInterface $appConfig, ) { parent::__construct(); } public function handle(): int { if (!$this->confirmToProceed()) { return 1; } $this->migrator->ensureTableExists(); $this->migrator->runUp( $this->getMigrationsDirectoryPath(), $this->getOutput(), $this->getStep(), ); return 0; } private function getStep(): int { return intval($this->option('step')); } private function getMigrationsDirectoryPath(): string { return $this->appConfig->get('clickhouse.migrations.path'); } }
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/src/Factory/ClickhouseClientFactory.php
src/Factory/ClickhouseClientFactory.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Laravel\Clickhouse\Factory; use ClickHouseDB\Client; use Cog\Laravel\Clickhouse\Exception\ClickhouseConfigException; final class ClickhouseClientFactory { public function __construct( private array $defaultConfig, ) {} /** * Creating a new instance of ClickHouse Client. * * @param array $config * @return Client * * @throws ClickhouseConfigException */ public function create( array $config = [], ): Client { if (count($config) === 0) { $config = $this->defaultConfig; } $options = []; if (isset($config['options'])) { $options = $config['options']; unset($config['options']); } $client = new Client($config); foreach ($options as $option => $value) { $method = $this->resolveOptionMutatorMethod($client, $option); $client->$method($value); } return $client; } /** * @throws ClickhouseConfigException */ private function resolveOptionMutatorMethod( Client $client, string $option, ): string { if (method_exists($client, $option)) { return $option; } if (method_exists($client, 'set' . ucwords($option))) { return 'set' . ucwords($option); } throw new ClickhouseConfigException("Unknown ClickHouse DB option {$option}"); } }
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/tests/AbstractTestCase.php
tests/AbstractTestCase.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Tests\Laravel\Clickhouse; use Cog\Laravel\Clickhouse\ClickhouseServiceProvider; use Orchestra\Testbench\TestCase as OrchestraTestCase; abstract class AbstractTestCase extends OrchestraTestCase { /** * {@inheritdoc} */ protected function getPackageProviders( $app, ): array { return [ ClickhouseServiceProvider::class, ]; } }
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/tests/Factory/ClickhouseClientFactoryTest.php
tests/Factory/ClickhouseClientFactoryTest.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Cog\Tests\Laravel\Clickhouse\Factory; use Cog\Laravel\Clickhouse\Exception\ClickhouseConfigException; use Cog\Laravel\Clickhouse\Factory\ClickhouseClientFactory; use Cog\Tests\Laravel\Clickhouse\AbstractTestCase; use Exception; final class ClickhouseClientFactoryTest extends AbstractTestCase { public function testInitializationWithMainConfig(): void { $clickhouse = new ClickhouseClientFactory( [ 'host' => 'example.com', 'port' => '9000', 'username' => 'test_user', 'password' => 'secret', 'options' => [ 'database' => 'test_database', 'timeout' => 150, 'connectTimeOut' => 151, ], ], ); $client = $clickhouse->create(); self::assertSame('example.com', $client->getConnectHost()); self::assertSame('9000', $client->getConnectPort()); self::assertSame('test_user', $client->getConnectUsername()); self::assertSame('secret', $client->getConnectPassword()); self::assertSame('test_database', $client->settings()->getDatabase()); self::assertSame(150, $client->getTimeout()); self::assertSame(151.0, $client->getConnectTimeOut()); } public function testInitializationWithNonExistsOption(): void { $clickhouseFactory = new ClickhouseClientFactory( [ 'host' => 'example.com', 'port' => '9000', 'username' => 'test_user', 'password' => 'secret', 'options' => [ 'database' => 'test_database', 'timeout' => 150, 'connectTimeOut' => 151, 'nonExistsOption' => 'value', ], ], ); try { $clickhouseFactory->create(); self::fail(ClickhouseConfigException::class . 'is not thrown'); } catch (Exception $exception) { self::assertSame(ClickhouseConfigException::class, get_class($exception)); } } }
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
cybercog/laravel-clickhouse
https://github.com/cybercog/laravel-clickhouse/blob/7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5/config/clickhouse.php
config/clickhouse.php
<?php /* * This file is part of Laravel ClickHouse. * * (c) Anton Komarev <anton@komarev.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); return [ /* |-------------------------------------------------------------------------- | ClickHouse Client Configuration |-------------------------------------------------------------------------- | | Here you can configure a connection to connect to the ClickHouse | database and specify additional configuration options. | */ 'connection' => [ 'host' => env('CLICKHOUSE_HOST', 'localhost'), 'port' => env('CLICKHOUSE_PORT', 8123), 'username' => env('CLICKHOUSE_USER', 'default'), 'password' => env('CLICKHOUSE_PASSWORD', ''), 'options' => [ 'database' => env('CLICKHOUSE_DATABASE', 'default'), 'timeout' => 1, 'connectTimeOut' => 2, ], ], /* |-------------------------------------------------------------------------- | ClickHouse Migration Settings |-------------------------------------------------------------------------- */ 'migrations' => [ 'table' => env('CLICKHOUSE_MIGRATION_TABLE', 'migrations'), 'path' => database_path('clickhouse-migrations'), ], ];
php
MIT
7b7aa5eb856c9d94ca450b7c7ff45d7a8a1381c5
2026-01-05T04:42:27.179183Z
false
alexpechkarev/geometry-library
https://github.com/alexpechkarev/geometry-library/blob/35839ed841805c8a0bc2fd8e4d5b5f600cb1416a/SphericalUtil.php
SphericalUtil.php
<?php namespace GeometryLibrary; /* * Copyright 2013 Google Inc. * https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/SphericalUtil.java * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use GeometryLibrary\MathUtil; class SphericalUtil { /** * Returns the heading from one LatLng to another LatLng. Headings are * expressed in degrees clockwise from North within the range [-180,180). * @return The heading in degrees clockwise from north. */ public static function computeHeading($from, $to) { // http://williams.best.vwh.net/avform.htm#Crs $fromLat = deg2rad($from['lat']); $fromLng = deg2rad($from['lng']); $toLat = deg2rad($to['lat']); $toLng = deg2rad($to['lng']); $dLng = $toLng - $fromLng; $heading = atan2( sin($dLng) * cos($toLat), cos($fromLat) * sin($toLat) - sin($fromLat) * cos($toLat) * cos($dLng)); return MathUtil::wrap(rad2deg($heading), -180, 180); } /** * Returns the LatLng resulting from moving a distance from an origin * in the specified heading (expressed in degrees clockwise from north). * @param from The LatLng from which to start. * @param distance The distance to travel. * @param heading The heading in degrees clockwise from north. */ public static function computeOffset($from, $distance, $heading) { $distance /= MathUtil::$earth_radius; $heading = deg2rad($heading); // http://williams.best.vwh.net/avform.htm#LL $fromLat = deg2rad($from['lat']); $fromLng = deg2rad($from['lng']); $cosDistance = cos($distance); $sinDistance = sin($distance); $sinFromLat = sin($fromLat); $cosFromLat = cos($fromLat); $sinLat = $cosDistance * $sinFromLat + $sinDistance * $cosFromLat * cos($heading); $dLng = atan2( $sinDistance * $cosFromLat * sin($heading), $cosDistance - $sinFromLat * $sinLat); return ['lat' => rad2deg(asin($sinLat)), 'lng' =>rad2deg($fromLng + $dLng)]; } /** * Returns the location of origin when provided with a LatLng destination, * meters travelled and original heading. Headings are expressed in degrees * clockwise from North. This function returns null when no solution is * available. * @param to The destination LatLng. * @param distance The distance travelled, in meters. * @param heading The heading in degrees clockwise from north. */ public static function computeOffsetOrigin($to, $distance, $heading) { $heading = deg2rad($heading); $distance /= MathUtil::$earth_radius; // http://lists.maptools.org/pipermail/proj/2008-October/003939.html $n1 = cos($distance); $n2 = sin($distance) * cos($heading); $n3 = sin($distance) * sin($heading); $n4 = sin(rad2deg($to['lat'])); // There are two solutions for b. b = n2 * n4 +/- sqrt(), one solution results // in the latitude outside the [-90, 90] range. We first try one solution and // back off to the other if we are outside that range. $n12 = $n1 * $n1; $discriminant = $n2 * $n2 * $n12 + $n12 * $n12 - $n12 * $n4 * $n4; if ($discriminant < 0) { // No real solution which would make sense in LatLng-space. return null; } $b = $n2 * $n4 + sqrt($discriminant); $b /= $n1 * $n1 + $n2 * $n2; $a = ($n4 - $n2 * $b) / $n1; $fromLatRadians = atan2($a, $b); if ($fromLatRadians < -M_PI / 2 || $fromLatRadians > M_PI / 2) { $b = $n2 * $n4 - sqrt($discriminant); $b /= $n1 * $n1 + $n2 * $n2; $fromLatRadians = atan2($a, $b); } if ($fromLatRadians < -M_PI / 2 || $fromLatRadians > M_PI / 2) { // No solution which would make sense in LatLng-space. return null; } $fromLngRadians = rad2deg($to['lng']) - atan2($n3, $n1 * cos($fromLatRadians) - $n2 * sin($fromLatRadians)); return ['lat' => rad2deg($fromLatRadians), 'lng' => rad2deg($fromLngRadians)]; } /** * Returns the LatLng which lies the given fraction of the way between the * origin LatLng and the destination LatLng. * @param from The LatLng from which to start. * @param to The LatLng toward which to travel. * @param fraction A fraction of the distance to travel. * @return The interpolated LatLng. */ public static function interpolate($from, $to, $fraction) { // http://en.wikipedia.org/wiki/Slerp $fromLat = deg2rad($from['lat']); $fromLng = deg2rad($from['lng']); $toLat = deg2rad($to['lat']); $toLng = deg2rad($to['lng']); $cosFromLat = cos($fromLat); $cosToLat = cos($toLat); // Computes Spherical interpolation coefficients. $angle = self::computeAngleBetween($from, $to); $sinAngle = sin($angle); if ($sinAngle < 1E-6) { return [ 'lat' => $from['lat'] + $fraction * ($to['lat'] - $from['lat']), 'lng' => $from['lng'] + $fraction * ($to['lng'] - $from['lng']) ]; } $a = sin((1 - $fraction) * $angle) / $sinAngle; $b = sin($fraction * $angle) / $sinAngle; // Converts from polar to vector and interpolate. $x = $a * $cosFromLat * cos($fromLng) + $b * $cosToLat * cos($toLng); $y = $a * $cosFromLat * sin($fromLng) + $b * $cosToLat * sin($toLng); $z = $a * sin($fromLat) + $b * sin($toLat); // Converts interpolated vector back to polar. $lat = atan2($z, sqrt($x * $x + $y * $y)); $lng = atan2($y, $x); return [ 'lat' => rad2deg($lat), 'lng' => rad2deg($lng)]; } /** * Returns distance on the unit sphere; the arguments are in radians. */ private static function distanceRadians( $lat1, $lng1, $lat2, $lng2) { return MathUtil::arcHav(MathUtil::havDistance($lat1, $lat2, $lng1 - $lng2)); } /** * Returns the angle between two LatLngs, in radians. This is the same as the distance * on the unit sphere. */ private static function computeAngleBetween($from, $to) { return self::distanceRadians(deg2rad($from['lat']), deg2rad($from['lng']), deg2rad($to['lat']), deg2rad($to['lng'])); } /** * Returns the distance between two LatLngs, in meters. */ public static function computeDistanceBetween( $from, $to) { return self::computeAngleBetween($from, $to) * MathUtil::$earth_radius; } /** * Returns the length of the given path, in meters, on Earth. */ public static function computeLength($path) { if (count($path) < 2) { return 0; } $length = 0; $prev = $path[0]; $prevLat = deg2rad($prev['lat']); $prevLng = deg2rad($prev['lng']); foreach($path as $point) { $lat = deg2rad($point['lat']); $lng = deg2rad($point['lng']); $length += self::distanceRadians($prevLat, $prevLng, $lat, $lng); $prevLat = $lat; $prevLng = $lng; } return $length * MathUtil::$earth_radius; } /** * Returns the area of a closed path on Earth. * @param path A closed path. * @return The path's area in square meters. */ public static function computeArea($path) { return abs(self::computeSignedArea($path)); } /** * Returns the signed area of a closed path on Earth. The sign of the area may be used to * determine the orientation of the path. * "inside" is the surface that does not contain the South Pole. * @param path A closed path. * @return The loop's area in square meters. */ public static function computeSignedArea($path) { return self::computeSignedAreaP($path, MathUtil::$earth_radius); } /** * Returns the signed area of a closed path on a sphere of given radius. * The computed area uses the same units as the radius squared. * Used by SphericalUtilTest. */ private static function computeSignedAreaP($path, $radius) { $size = count($path); if ($size < 3) { return 0; } $total = 0; $prev = $path[$size - 1]; $prevTanLat = tan((M_PI / 2 - deg2rad($prev['lat'])) / 2); $prevLng = deg2rad($prev['lng']); // For each edge, accumulate the signed area of the triangle formed by the North Pole // and that edge ("polar triangle"). foreach($path as $point) { $tanLat = tan((M_PI / 2 - deg2rad($point['lat'])) / 2); $lng = deg2rad($point['lng']); $total += self::polarTriangleArea($tanLat, $lng, $prevTanLat, $prevLng); $prevTanLat = $tanLat; $prevLng = $lng; } return $total * ($radius * $radius); } /** * Returns the signed area of a triangle which has North Pole as a vertex. * Formula derived from "Area of a spherical triangle given two edges and the included angle" * as per "Spherical Trigonometry" by Todhunter, page 71, section 103, point 2. * See http://books.google.com/books?id=3uBHAAAAIAAJ&pg=PA71 * The arguments named "tan" are tan((pi/2 - latitude)/2). */ private static function polarTriangleArea($tan1, $lng1, $tan2, $lng2) { $deltaLng = $lng1 - $lng2; $t = $tan1 * $tan2; return 2 * atan2($t * sin($deltaLng), 1 + $t * cos($deltaLng)); } } ?>
php
MIT
35839ed841805c8a0bc2fd8e4d5b5f600cb1416a
2026-01-05T04:42:33.180245Z
false
alexpechkarev/geometry-library
https://github.com/alexpechkarev/geometry-library/blob/35839ed841805c8a0bc2fd8e4d5b5f600cb1416a/PolyUtil.php
PolyUtil.php
<?php namespace GeometryLibrary; /* * Copyright 2013 Google Inc. * * https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/PolyUtil.java * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use GeometryLibrary\MathUtil; use GeometryLibrary\SphericalUtil; class PolyUtil { const DEFAULT_TOLERANCE = 0.1; // meters. /** * Returns tan(latitude-at-lng3) on the great circle (lat1, lng1) to (lat2, lng2). lng1==0. * See http://williams.best.vwh.net/avform.htm . */ private static function tanLatGC( $lat1, $lat2, $lng2, $lng3) { return (tan($lat1) * sin($lng2 - $lng3) + tan($lat2) * sin($lng3)) / sin($lng2); } /** * Returns mercator(latitude-at-lng3) on the Rhumb line (lat1, lng1) to (lat2, lng2). lng1==0. */ private static function mercatorLatRhumb( $lat1, $lat2, $lng2, $lng3) { return (MathUtil::mercator($lat1) * ($lng2 - $lng3) + MathUtil::mercator($lat2) * $lng3) / $lng2; } /** * Computes whether the vertical segment (lat3, lng3) to South Pole intersects the segment * (lat1, lng1) to (lat2, lng2). * Longitudes are offset by -lng1; the implicit lng1 becomes 0. */ private static function intersects( $lat1, $lat2, $lng2, $lat3, $lng3, $geodesic) { // Both ends on the same side of lng3. if (($lng3 >= 0 && $lng3 >= $lng2) || ($lng3 < 0 && $lng3 < $lng2)) { return false; } // Point is South Pole. if ($lat3 <= -M_PI/2) { return false; } // Any segment end is a pole. if ($lat1 <= -M_PI/2 || $lat2 <= -M_PI/2 || $lat1 >= M_PI/2 || $lat2 >= M_PI/2) { return false; } if ($lng2 <= -M_PI) { return false; } $linearLat = ($lat1 * ($lng2 - $lng3) + $lat2 * $lng3) / $lng2; // Northern hemisphere and point under lat-lng line. if ($lat1 >= 0 && $lat2 >= 0 && $lat3 < $linearLat) { return false; } // Southern hemisphere and point above lat-lng line. if ($lat1 <= 0 && $lat2 <= 0 && $lat3 >= $linearLat) { return true; } // North Pole. if ($lat3 >= M_PI/2) { return true; } // Compare lat3 with latitude on the GC/Rhumb segment corresponding to lng3. // Compare through a strictly-increasing function (tan() or mercator()) as convenient. return $geodesic ? tan($lat3) >= self::tanLatGC($lat1, $lat2, $lng2, $lng3) : MathUtil::mercator($lat3) >= self::mercatorLatRhumb($lat1, $lat2, $lng2, $lng3); } /** * Computes whether the given point lies inside the specified polygon. * The polygon is always cosidered closed, regardless of whether the last point equals * the first or not. * Inside is defined as not containing the South Pole -- the South Pole is always outside. * The polygon is formed of great circle segments if geodesic is true, and of rhumb * (loxodromic) segments otherwise. */ public static function containsLocation($point, $polygon, $geodesic = false) { $size = count( $polygon ); if ($size == 0) { return false; } $lat3 = deg2rad( $point['lat'] ); $lng3 = deg2rad( $point['lng'] ); $prev = $polygon[$size - 1]; $lat1 = deg2rad( $prev['lat'] ); $lng1 = deg2rad( $prev['lng'] ); $nIntersect = 0; foreach($polygon as $key => $val) { $dLng3 = MathUtil::wrap($lng3 - $lng1, -M_PI, M_PI); // Special case: point equal to vertex is inside. if ($lat3 == $lat1 && $dLng3 == 0) { return true; } $lat2 = deg2rad($val['lat']); $lng2 = deg2rad($val['lng']); // Offset longitudes by -lng1. if (self::intersects($lat1, $lat2, MathUtil::wrap($lng2 - $lng1, -M_PI, M_PI), $lat3, $dLng3, $geodesic)) { ++$nIntersect; } $lat1 = $lat2; $lng1 = $lng2; } return ($nIntersect & 1) != 0; } /** * Computes whether the given point lies on or near the edge of a polygon, within a specified * tolerance in meters. The polygon edge is composed of great circle segments if geodesic * is true, and of Rhumb segments otherwise. The polygon edge is implicitly closed -- the * closing segment between the first point and the last point is included. */ public static function isLocationOnEdge($point, $polygon, $tolerance = self::DEFAULT_TOLERANCE, $geodesic = true) { return self::isLocationOnEdgeOrPath($point, $polygon, true, $geodesic, $tolerance); } /** * Computes whether the given point lies on or near a polyline, within a specified * tolerance in meters. The polyline is composed of great circle segments if geodesic * is true, and of Rhumb segments otherwise. The polyline is not closed -- the closing * segment between the first point and the last point is not included. */ public static function isLocationOnPath($point, $polyline, $tolerance = self::DEFAULT_TOLERANCE, $geodesic = true) { return self::isLocationOnEdgeOrPath($point, $polyline, false, $geodesic, $tolerance); } private static function isLocationOnEdgeOrPath($point, $poly, $closed, $geodesic, $toleranceEarth) { $size = count( $poly ); if ($size == 0) { return false; } $tolerance = $toleranceEarth / MathUtil::$earth_radius; $havTolerance = MathUtil::hav($tolerance); $lat3 = deg2rad($point['lat']); $lng3 = deg2rad($point['lng']); $prev = !empty($closed) ? $poly[$size - 1] : $poly[0]; $lat1 = deg2rad($prev['lat']); $lng1 = deg2rad($prev['lng']); if ($geodesic) { foreach($poly as $val) { $lat2 = deg2rad($val['lat']); $lng2 = deg2rad($val['lng']); if ( self::isOnSegmentGC($lat1, $lng1, $lat2, $lng2, $lat3, $lng3, $havTolerance)) { return true; } $lat1 = $lat2; $lng1 = $lng2; } } else { // We project the points to mercator space, where the Rhumb segment is a straight line, // and compute the geodesic distance between point3 and the closest point on the // segment. This method is an approximation, because it uses "closest" in mercator // space which is not "closest" on the sphere -- but the error is small because // "tolerance" is small. $minAcceptable = $lat3 - $tolerance; $maxAcceptable = $lat3 + $tolerance; $y1 = MathUtil::mercator($lat1); $y3 = MathUtil::mercator($lat3); $xTry = []; foreach($poly as $val) { $lat2 = deg2rad($val['lat']); $y2 = MathUtil::mercator($lat2); $lng2 = deg2rad($val['lng']); if (max($lat1, $lat2) >= $minAcceptable && min($lat1, $lat2) <= $maxAcceptable) { // We offset longitudes by -lng1; the implicit x1 is 0. $x2 = MathUtil::wrap($lng2 - $lng1, -M_PI, M_PI); $x3Base = MathUtil::wrap($lng3 - $lng1, -M_PI, M_PI); $xTry[0] = $x3Base; // Also explore wrapping of x3Base around the world in both directions. $xTry[1] = $x3Base + 2 * M_PI; $xTry[2] = $x3Base - 2 * M_PI; foreach($xTry as $x3) { $dy = $y2 - $y1; $len2 = $x2 * $x2 + $dy * $dy; $t = $len2 <= 0 ? 0 : MathUtil::clamp(($x3 * $x2 + ($y3 - $y1) * $dy) / $len2, 0, 1); $xClosest = $t * $x2; $yClosest = $y1 + $t * $dy; $latClosest = MathUtil::inverseMercator($yClosest); $havDist = MathUtil::havDistance($lat3, $latClosest, $x3 - $xClosest); if ($havDist < $havTolerance) { return true; } } } $lat1 = $lat2; $lng1 = $lng2; $y1 = $y2; } } return false; } /** * Returns sin(initial bearing from (lat1,lng1) to (lat3,lng3) minus initial bearing * from (lat1, lng1) to (lat2,lng2)). */ private static function sinDeltaBearing( $lat1, $lng1, $lat2, $lng2, $lat3, $lng3) { $sinLat1 = sin($lat1); $cosLat2 = cos($lat2); $cosLat3 = cos($lat3); $lat31 = $lat3 - $lat1; $lng31 = $lng3 - $lng1; $lat21 = $lat2 - $lat1; $lng21 = $lng2 - $lng1; $a = sin($lng31) * $cosLat3; $c = sin($lng21) * $cosLat2; $b = sin($lat31) + 2 * $sinLat1 * $cosLat3 * MathUtil::hav($lng31); $d = sin($lat21) + 2 * $sinLat1 * $cosLat2 * MathUtil::hav($lng21); $denom = ($a * $a + $b * $b) * ($c * $c + $d * $d); return $denom <= 0 ? 1 : ($a * $d - $b * $c) / sqrt($denom); } private static function isOnSegmentGC( $lat1, $lng1, $lat2, $lng2, $lat3, $lng3, $havTolerance) { $havDist13 = MathUtil::havDistance($lat1, $lat3, $lng1 - $lng3); if ($havDist13 <= $havTolerance) { return true; } $havDist23 = MathUtil::havDistance($lat2, $lat3, $lng2 - $lng3); if ($havDist23 <= $havTolerance) { return true; } $sinBearing = self::sinDeltaBearing($lat1, $lng1, $lat2, $lng2, $lat3, $lng3); $sinDist13 = MathUtil::sinFromHav($havDist13); $havCrossTrack = MathUtil::havFromSin($sinDist13 * $sinBearing); if ($havCrossTrack > $havTolerance) { return false; } $havDist12 = MathUtil::havDistance($lat1, $lat2, $lng1 - $lng2); $term = $havDist12 + $havCrossTrack * (1 - 2 * $havDist12); if ($havDist13 > $term || $havDist23 > $term) { return false; } if ($havDist12 < 0.74) { return true; } $cosCrossTrack = 1 - 2 * $havCrossTrack; $havAlongTrack13 = ($havDist13 - $havCrossTrack) / $cosCrossTrack; $havAlongTrack23 = ($havDist23 - $havCrossTrack) / $cosCrossTrack; $sinSumAlongTrack = MathUtil::sinSumFromHav($havAlongTrack13, $havAlongTrack23); return $sinSumAlongTrack > 0; // Compare with half-circle == PI using sign of sin(). } /** * Computes the distance on the sphere between the point p and the line segment start to end. * * @param p the point to be measured * @param start the beginning of the line segment * @param end the end of the line segment * @return the distance in meters (assuming spherical earth) */ public static function distanceToLine($p, $start, $end) { if ($start == $end) { return SphericalUtil::computeDistanceBetween($end, $p); } $s0lat = deg2rad($p['lat']); $s0lng = deg2rad($p['lng']); $s1lat = deg2rad($start['lat']); $s1lng = deg2rad($start['lng']); $s2lat = deg2rad($end['lat']); $s2lng = deg2rad($end['lng']); $s2s1lat = $s2lat - $s1lat; $s2s1lng = $s2lng - $s1lng; $u = (($s0lat - $s1lat) * $s2s1lat + ($s0lng - $s1lng) * $s2s1lng) / ($s2s1lat * $s2s1lat + $s2s1lng * $s2s1lng); if ($u <= 0) { return SphericalUtil::computeDistanceBetween($p, $start); } if ($u >= 1) { return SphericalUtil::computeDistanceBetween($p, $end); } $su = ['lat' => $start['lat'] + $u * ($end['lat'] - $start['lat']), 'lng' => $start['lng'] + $u * ($end['lng'] - $start['lng'])]; return SphericalUtil::computeDistanceBetween($p, $su); } /** * Decodes an encoded path string into a sequence of LatLngs. */ public static function decode($encodedPath) { $len = strlen( $encodedPath ) -1; // For speed we preallocate to an upper bound on the final length, then // truncate the array before returning. $path = []; $index = 0; $lat = 0; $lng = 0; while( $index < $len) { $result = 1; $shift = 0; $b; do { $b = ord($encodedPath[$index++]) - 63 - 1; $result += $b << $shift; $shift += 5; } while ($b >= hexdec("0x1f")); $lat += ($result & 1) != 0 ? ~($result >> 1) : ($result >> 1); $result = 1; $shift = 0; do { $b = ord($encodedPath[$index++]) - 63 - 1; $result += $b << $shift; $shift += 5; } while ($b >= hexdec("0x1f")); $lng += ($result & 1) != 0 ? ~($result >> 1) : ($result >> 1); array_push($path, ['lat' => $lat * 1e-5, 'lng' => $lng * 1e-5]); } return $path; } /** * Encodes a sequence of LatLngs into an encoded path string. */ public static function encode($path) { $lastLat = 0; $lastLng = 0; $result = ''; foreach( $path as $point ) { $lat = round( $point['lat'] * 1e5); $lng = round( $point['lng'] * 1e5); $dLat = $lat - $lastLat; $dLng = $lng - $lastLng; $result.=self::enc($dLat); $result.=self::enc($dLng); $lastLat = $lat; $lastLng = $lng; } return $result; } private static function enc($v) { $v = $v < 0 ? ~($v << 1) : $v << 1; $result = ''; while ($v >= 0x20) { $result.= chr((int) ((0x20 | ($v & 0x1f)) + 63)); $v >>= 5; } $result.=chr((int) ($v + 63)); return $result; } } ?>
php
MIT
35839ed841805c8a0bc2fd8e4d5b5f600cb1416a
2026-01-05T04:42:33.180245Z
false
alexpechkarev/geometry-library
https://github.com/alexpechkarev/geometry-library/blob/35839ed841805c8a0bc2fd8e4d5b5f600cb1416a/MathUtil.php
MathUtil.php
<?php namespace GeometryLibrary; /* * Copyright 2013 Google Inc. * https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/MathUtil.java * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class MathUtil { /** * The earth's radius, in meters. * Mean radius as defined by IUGG. * https://developers.google.com/maps/documentation/javascript/reference/geometry * Utility functions for computing geodesic angles, distances and areas. * The default radius is Earth's radius of 6378137 meters. * * 2021-10-18 - Earth's radius updated in accordance with Google Maps JavaScript API; */ public static $earth_radius = 6378137; /** * Change the earth radius for different earth points */ public static function changeEarthRadius($newRadius) { self::$earth_radius = $newRadius; } /** * Restrict x to the range [low, high]. */ public static function clamp( $x, $low, $high) { return $x < $low ? $low : ($x > $high ? $high : $x); } /** * Wraps the given value into the inclusive-exclusive interval between min and max. * @param n The value to wrap. * @param min The minimum. * @param max The maximum. */ public static function wrap($n, $min, $max) { return ($n >= $min && $n < $max) ? $n : (self::mod($n - $min, $max - $min) + $min); } /** * Returns the non-negative remainder of x / m. * @param x The operand. * @param m The modulus. */ public static function mod($x, $m) { return (($x % $m) + $m) % $m; } /** * Returns mercator Y corresponding to latitude. * See http://en.wikipedia.org/wiki/Mercator_projection . */ public static function mercator($lat) { return log(tan($lat * 0.5 + M_PI/4)); } /** * Returns latitude from mercator Y. */ public static function inverseMercator($y) { return 2 * atan(exp($y)) - M_PI / 2; } /** * Returns haversine(angle-in-radians). * hav(x) == (1 - cos(x)) / 2 == sin(x / 2)^2. */ public static function hav($x) { $sinHalf = sin($x * 0.5); return $sinHalf * $sinHalf; } /** * Computes inverse haversine. Has good numerical stability around 0. * arcHav(x) == acos(1 - 2 * x) == 2 * asin(sqrt(x)). * The argument must be in [0, 1], and the result is positive. */ public static function arcHav($x) { return 2 * asin(sqrt($x)); } // Given h==hav(x), returns sin(abs(x)). public static function sinFromHav($h) { return 2 * sqrt($h * (1 - $h)); } // Returns hav(asin(x)). public static function havFromSin($x) { $x2 = $x * $x; return $x2 / (1 + sqrt(1 - $x2)) * .5; } // Returns sin(arcHav(x) + arcHav(y)). public static function sinSumFromHav($x, $y) { $a = sqrt($x * (1 - $x)); $b = sqrt($y * (1 - $y)); return 2 * ($a + $b - 2 * ($a * $y + $b * $x)); } /** * Returns hav() of distance from (lat1, lng1) to (lat2, lng2) on the unit sphere. */ public static function havDistance($lat1, $lat2, $dLng) { return self::hav($lat1 - $lat2) + self::hav($dLng) * cos($lat1) * cos($lat2); } } ?>
php
MIT
35839ed841805c8a0bc2fd8e4d5b5f600cb1416a
2026-01-05T04:42:33.180245Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter08/8.php
Chapter08/8.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class TreeNode { public $data = NULL; public $children = []; public function __construct(string $data = NULL) { $this->data = $data; } public function addChildren(TreeNode $node) { $this->children[] = $node; } } class Tree { public $root = NULL; public function __construct(TreeNode $node) { $this->root = $node; } public function BFS(TreeNode $node): SplQueue { $queue = new SplQueue; $visited = new SplQueue; $queue->enqueue($node); while (!$queue->isEmpty()) { $current = $queue->dequeue(); $visited->enqueue($current); foreach ($current->children as $child) { $queue->enqueue($child); } } return $visited; } } try { $root = new TreeNode("8"); $tree = new Tree($root); $node1 = new TreeNode("3"); $node2 = new TreeNode("10"); $root->addChildren($node1); $root->addChildren($node2); $node3 = new TreeNode("1"); $node4 = new TreeNode("6"); $node5 = new TreeNode("14"); $node1->addChildren($node3); $node1->addChildren($node4); $node2->addChildren($node5); $node6 = new TreeNode("4"); $node7 = new TreeNode("7"); $node8 = new TreeNode("13"); $node4->addChildren($node6); $node4->addChildren($node7); $node5->addChildren($node8); $visited = $tree->BFS($tree->root); while (!$visited->isEmpty()) { echo $visited->dequeue()->data . "\n"; } } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter08/4.php
Chapter08/4.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function repetitiveBinarySearch(array $numbers, int $neeedle): int { $low = 0; $high = count($numbers) - 1; $firstOccurrence = -1; while ($low <= $high) { $mid = (int) (($low + $high) / 2); if ($numbers[$mid] === $neeedle) { $firstOccurrence = $mid; $high = $mid - 1; } else if ($numbers[$mid] > $neeedle) { $high = $mid - 1; } else { $low = $mid + 1; } } return $firstOccurrence; } $numbers = [1,2,2,2,2,2,2,2,2,3,3,3,3,3,4,4,5,5]; $number = 2; $pos = repetitiveBinarySearch($numbers, $number); if ($pos >= 0) { echo "$number Found at position $pos \n"; } else { echo "$number Not found \n"; } $number = 5; $pos = repetitiveBinarySearch($numbers, $number); if ($pos >= 0) { echo "$number Found at position $pos \n"; } else { echo "$number Not found \n"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter08/6.php
Chapter08/6.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function binarySearch(array $numbers, int $neeedle, int $low, int $high): int { if ($high < $low) { return -1; } $mid = (int) (($low + $high) / 2); if ($numbers[$mid] > $neeedle) { return binarySearch($numbers, $neeedle, $low, $mid - 1); } else if ($numbers[$mid] < $neeedle) { return binarySearch($numbers, $neeedle, $mid + 1, $high); } else { return $mid; } } function exponentialSearch(array $arr, int $key): int { $size = count($arr); if ($size == 0) return -1; $bound = 1; while ($bound < $size && $arr[$bound] < $key) { $bound *= 2; } return binarySearch($arr, $key, intval($bound / 2), min($bound, $size)); } $numbers = range(1, 200, 5); $number = 31; if (exponentialSearch($numbers, $number) >= 0) { echo "$number Found \n"; } else { echo "$number Not found \n"; } $number = 196; if (exponentialSearch($numbers, $number) >= 0) { echo "$number Found \n"; } else { echo "$number Not found \n"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter08/9.php
Chapter08/9.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class TreeNode { public $data = NULL; public $children = []; public function __construct(string $data = NULL) { $this->data = $data; } public function addChildren(TreeNode $node) { $this->children[] = $node; } } class Tree { public $root = NULL; public $visited; public function __construct(TreeNode $node) { $this->root = $node; $this->visited = new SplQueue; } public function DFS(TreeNode $node) { $this->visited->enqueue($node); if($node->children){ foreach ($node->children as $child) { $this->DFS($child); } } } } try { $root = new TreeNode("8"); $tree = new Tree($root); $node1 = new TreeNode("3"); $node2 = new TreeNode("10"); $root->addChildren($node1); $root->addChildren($node2); $node3 = new TreeNode("1"); $node4 = new TreeNode("6"); $node5 = new TreeNode("14"); $node1->addChildren($node3); $node1->addChildren($node4); $node2->addChildren($node5); $node6 = new TreeNode("4"); $node7 = new TreeNode("7"); $node8 = new TreeNode("13"); $node4->addChildren($node6); $node4->addChildren($node7); $node5->addChildren($node8); $tree->DFS($tree->root); $visited = $tree->visited; while (!$visited->isEmpty()) { echo $visited->dequeue()->data . "\n"; } } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter08/7.php
Chapter08/7.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $arr = []; $count = rand(10, 30); for($i = 0; $i<$count;$i++) { $val = rand(1,500); $arr[$val] = $val; } $number = 100; if(isset($arr[$number])) { echo "$number found "; } else { echo "$number not found"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter08/10.php
Chapter08/10.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class TreeNode { public $data = NULL; public $children = []; public function __construct(string $data = NULL) { $this->data = $data; } public function addChildren(TreeNode $node) { $this->children[] = $node; } } class Tree { public $root = NULL; public function __construct(TreeNode $node) { $this->root = $node; } public function DFS(TreeNode $node): SplQueue { $stack = new SplStack; $visited = new SplQueue; $stack->push($node); while (!$stack->isEmpty()) { $current = $stack->pop(); $visited->enqueue($current); $current->children = array_reverse($current->children); foreach ($current->children as $child) { $stack->push($child); } } return $visited; } } try { $root = new TreeNode("8"); $tree = new Tree($root); $node1 = new TreeNode("3"); $node2 = new TreeNode("10"); $root->addChildren($node1); $root->addChildren($node2); $node3 = new TreeNode("1"); $node4 = new TreeNode("6"); $node5 = new TreeNode("14"); $node1->addChildren($node3); $node1->addChildren($node4); $node2->addChildren($node5); $node6 = new TreeNode("4"); $node7 = new TreeNode("7"); $node8 = new TreeNode("13"); $node4->addChildren($node6); $node4->addChildren($node7); $node5->addChildren($node8); $visited = $tree->DFS($tree->root); while (!$visited->isEmpty()) { echo $visited->dequeue()->data . "\n"; } } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter08/5.php
Chapter08/5.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function interpolationSearch(array $arr, int $key): int { $low = 0; $high = count($arr) - 1; while ($arr[$high] != $arr[$low] && $key >= $arr[$low] && $key <= $arr[$high]) { $mid = intval($low + (($key - $arr[$low]) * ($high - $low) / ($arr[$high] - $arr[$low]))); if ($arr[$mid] < $key) $low = $mid + 1; else if ($key < $arr[$mid]) $high = $mid - 1; else return $mid; } if ($key == $arr[$low]) return $low; else return -1; } $numbers = range(1, 200, 5); $number = 31; if (interpolationSearch($numbers, $number) >= 0) { echo "$number Found \n"; } else { echo "$number Not found \n"; } $number = 196; if (interpolationSearch($numbers, $number) >= 0) { echo "$number Found \n"; } else { echo "$number Not found \n"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter08/3.php
Chapter08/3.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function binarySearch(array $numbers, int $neeedle, int $low, int $high): int { if ($high < $low) { return -1; } $mid = (int) (($low + $high) / 2); if ($numbers[$mid] > $neeedle) { return binarySearch($numbers, $neeedle, $low, $mid - 1); } else if ($numbers[$mid] < $neeedle) { return binarySearch($numbers, $neeedle, $mid + 1, $high); } else { return $mid; } } $numbers = range(1, 200, 5); $number = 31; if (binarySearch($numbers, $number, 0, count($numbers) - 1) >= 0) { echo "$number Found \n"; } else { echo "$number Not found \n"; } $number = 500; if (binarySearch($numbers, $number, 0, count($numbers) - 1) >= 0) { echo "$number Found \n"; } else { echo "$number Not found \n"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter08/1.php
Chapter08/1.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function search(array $numbers, int $neeedle): bool { $totalItems = count($numbers); for ($i = 0; $i < $totalItems; $i++) { if($numbers[$i] === $neeedle){ return TRUE; } } return FALSE; } $numbers = range(1, 200, 5); if (search($numbers, 31)) { echo "Found"; } else { echo "Not found"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter08/2.php
Chapter08/2.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function binarySearch(array $numbers, int $neeedle): bool { $low = 0; $high = count($numbers)-1; while ($low <= $high) { $mid = (int) (($low + $high) / 2); if ($numbers[$mid] > $neeedle) { $high = $mid - 1; } else if ($numbers[$mid] < $neeedle) { $low = $mid + 1; } else { return TRUE; } } return FALSE; } $numbers = range(1, 200, 5); $number = 31; if (binarySearch($numbers, $number) !== FALSE) { echo "$number Found \n"; } else { echo "$number Not found \n"; } $number = 196; if (binarySearch($numbers, $number) !== FALSE) { echo "$number Found \n"; } else { echo "$number Not found \n"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/8.php
Chapter04/8.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class ListNode { public $data = NULL; public $next = NULL; public $priority = NULL; public function __construct(string $data = NULL, int $priority = NULL) { $this->data = $data; $this->priority = $priority; } } class LinkedList implements Iterator { private $_firstNode = NULL; private $_totalNode = 0; private $_currentNode = NULL; private $_currentPosition = 0; public function insert(string $data = NULL, int $priority = NULL) { $newNode = new ListNode($data, $priority); $this->_totalNode++; if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; } else { $previous = $this->_firstNode; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->priority < $priority) { if ($currentNode == $this->_firstNode) { $previous = $this->_firstNode; $this->_firstNode = $newNode; $newNode->next = $previous; return; } $newNode->next = $currentNode; $previous->next = $newNode; return; } $previous = $currentNode; $currentNode = $currentNode->next; } } return TRUE; } public function deleteFirst() { if ($this->_firstNode !== NULL) { if ($this->_firstNode->next !== NULL) { $this->_firstNode = $this->_firstNode->next; } else { $this->_firstNode = NULL; } $this->_totalNode--; return TRUE; } return FALSE; } public function getSize() { return $this->_totalNode; } public function current() { return $this->_currentNode->data; } public function next() { $this->_currentPosition++; $this->_currentNode = $this->_currentNode->next; } public function key() { return $this->_currentPosition; } public function rewind() { $this->_currentPosition = 0; $this->_currentNode = $this->_firstNode; } public function valid() { return $this->_currentNode !== NULL; } public function getNthNode(int $n = 0) { $count = 1; if ($this->_firstNode !== NULL && $n <= $this->_totalNode) { $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($count === $n) { return $currentNode; } $count++; $currentNode = $currentNode->next; } } } public function display() { echo "Total book titles: " . $this->_totalNode . "\n"; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { echo $currentNode->data . "\n"; $currentNode = $currentNode->next; } } } interface Queue { public function enqueue(string $item, int $p); public function dequeue(); public function peek(); public function isEmpty(); } class AgentQueue implements Queue { private $limit; private $queue; public function __construct(int $limit = 20) { $this->limit = $limit; $this->queue = new LinkedList(); } public function dequeue(): string { if ($this->isEmpty()) { throw new UnderflowException('Queue is empty'); } else { $lastItem = $this->peek(); $this->queue->deleteFirst(); return $lastItem; } } public function enqueue(string $newItem, int $priority) { if ($this->queue->getSize() < $this->limit) { $this->queue->insert($newItem, $priority); } else { throw new OverflowException('Queue is full'); } } public function peek(): string { return $this->queue->getNthNode(1)->data; } public function isEmpty(): bool { return $this->queue->getSize() == 0; } public function display() { $this->queue->display(); } } try { $agents = new AgentQueue(10); $agents->enqueue("Fred", 1); $agents->enqueue("John", 2); $agents->enqueue("Keith", 3); $agents->enqueue("Adiyan", 4); $agents->enqueue("Mikhael", 2); $agents->display(); echo $agents->dequeue()."\n"; echo $agents->dequeue()."\n"; } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/4.php
Chapter04/4.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function expressionChecker(string $expression): bool { $valid = TRUE; $stack = new SplStack(); for ($i = 0; $i < strlen($expression); $i++) { $char = substr($expression, $i, 1); switch ($char) { case '(': case '{': case '[': $stack->push($char); break; case ')': case '}': case ']': if ($stack->isEmpty()) { $valid = FALSE; } else { $last = $stack->pop(); if (($char == ")" && $last != "(") || ($char == "}" && $last != "{") || ($char == "]" && $last != "[")) { $valid = FALSE; } } break; } if (!$valid) break; } if (!$stack->isEmpty()) { $valid = FALSE; } return $valid; } $expressions = []; $expressions[] = "8 * (9 -2) + { (4 * 5) / ( 2 * 2) }"; $expressions[] = "5 * 8 * 9 / ( 3 * 2 ) )"; $expressions[] = "[{ (2 * 7) + ( 15 - 3) ]"; foreach ($expressions as $expression) { $valid = expressionChecker($expression); if ($valid) { echo "Expression is valid \n"; } else { echo "Expression is not valid \n"; } }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/6.php
Chapter04/6.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class ListNode { public $data = NULL; public $next = NULL; public function __construct(string $data = NULL) { $this->data = $data; } } class LinkedList implements Iterator { private $_firstNode = NULL; private $_totalNode = 0; private $_currentNode = NULL; private $_currentPosition = 0; public function insert(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; } else { $currentNode = $this->_firstNode; while ($currentNode->next !== NULL) { $currentNode = $currentNode->next; } $currentNode->next = $newNode; } $this->_totalNode++; return TRUE; } public function insertAtFirst(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; } else { $currentFirstNode = $this->_firstNode; $this->_firstNode = &$newNode; $newNode->next = $currentFirstNode; } $this->_totalNode++; return TRUE; } public function search(string $data = NULL) { if ($this->_totalNode) { $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $data) { return $currentNode; } $currentNode = $currentNode->next; } } return FALSE; } public function insertBefore(string $data = NULL, string $query = NULL) { $newNode = new ListNode($data); if ($this->_firstNode) { $previous = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { $newNode->next = $currentNode; $previous->next = $newNode; $this->_totalNode++; break; } $previous = $currentNode; $currentNode = $currentNode->next; } } } public function insertAfter(string $data = NULL, string $query = NULL) { $newNode = new ListNode($data); if ($this->_firstNode) { $nextNode = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { if ($nextNode !== NULL) { $newNode->next = $nextNode; } $currentNode->next = $newNode; $this->_totalNode++; break; } $currentNode = $currentNode->next; $nextNode = $currentNode->next; } } } public function deleteFirst() { if ($this->_firstNode !== NULL) { if ($this->_firstNode->next !== NULL) { $this->_firstNode = $this->_firstNode->next; } else { $this->_firstNode = NULL; } $this->_totalNode--; return TRUE; } return FALSE; } public function deleteLast() { if ($this->_firstNode !== NULL) { $currentNode = $this->_firstNode; if ($currentNode->next === NULL) { $this->_firstNode = NULL; } else { $previousNode = NULL; while ($currentNode->next !== NULL) { $previousNode = $currentNode; $currentNode = $currentNode->next; } $previousNode->next = NULL; $this->_totalNode--; return TRUE; } } return FALSE; } public function delete(string $query = NULL) { if ($this->_firstNode) { $previous = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { if ($currentNode->next === NULL) { $previous->next = NULL; } else { $previous->next = $currentNode->next; } $this->_totalNode--; break; } $previous = $currentNode; $currentNode = $currentNode->next; } } } public function reverse() { if ($this->_firstNode !== NULL) { if ($this->_firstNode->next !== NULL) { $reversedList = NULL; $next = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { $next = $currentNode->next; $currentNode->next = $reversedList; $reversedList = $currentNode; $currentNode = $next; } $this->_firstNode = $reversedList; } } } public function getNthNode(int $n = 0) { $count = 1; if ($this->_firstNode !== NULL && $n <= $this->_totalNode) { $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($count === $n) { return $currentNode; } $count++; $currentNode = $currentNode->next; } } } public function display() { echo "Total book titles: " . $this->_totalNode . "\n"; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { echo $currentNode->data . "\n"; $currentNode = $currentNode->next; } } public function getSize() { return $this->_totalNode; } public function current() { return $this->_currentNode->data; } public function next() { $this->_currentPosition++; $this->_currentNode = $this->_currentNode->next; } public function key() { return $this->_currentPosition; } public function rewind() { $this->_currentPosition = 0; $this->_currentNode = $this->_firstNode; } public function valid() { return $this->_currentNode !== NULL; } } interface Queue { public function enqueue(string $item); public function dequeue(); public function peek(); public function isEmpty(); } class AgentQueue implements Queue { private $limit; private $queue; public function __construct(int $limit = 20) { $this->limit = $limit; $this->queue = new LinkedList(); } public function dequeue(): string { if ($this->isEmpty()) { throw new UnderflowException('Queue is empty'); } else { $lastItem = $this->peek(); $this->queue->deleteFirst(); return $lastItem; } } public function enqueue(string $newItem) { if ($this->queue->getSize() < $this->limit) { $this->queue->insert($newItem); } else { throw new OverflowException('Queue is full'); } } public function peek(): string { return $this->queue->getNthNode(1)->data; } public function isEmpty(): bool { return $this->queue->getSize() == 0; } } try { $agents = new AgentQueue(10); $agents->enqueue("Fred"); $agents->enqueue("John"); $agents->enqueue("Keith"); $agents->enqueue("Adiyan"); $agents->enqueue("Mikhael"); echo $agents->dequeue()."\n"; echo $agents->dequeue()."\n"; echo $agents->peek()."\n"; } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/11.php
Chapter04/11.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class ListNode { public $data = NULL; public $next = NULL; public function __construct(string $data = NULL) { $this->data = $data; } } class LinkedList implements Iterator { private $_firstNode = NULL; private $_totalNode = 0; private $_currentNode = NULL; private $_currentPosition = 0; public function insert(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; } else { $currentNode = $this->_firstNode; while ($currentNode->next !== NULL) { $currentNode = $currentNode->next; } $currentNode->next = $newNode; } $this->_totalNode++; return TRUE; } public function insertAtFirst(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; } else { $currentFirstNode = $this->_firstNode; $this->_firstNode = &$newNode; $newNode->next = $currentFirstNode; } $this->_totalNode++; return TRUE; } public function search(string $data = NULL) { if ($this->_totalNode) { $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $data) { return $currentNode; } $currentNode = $currentNode->next; } } return FALSE; } public function insertBefore(string $data = NULL, string $query = NULL) { $newNode = new ListNode($data); if ($this->_firstNode) { $previous = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { $newNode->next = $currentNode; $previous->next = $newNode; $this->_totalNode++; break; } $previous = $currentNode; $currentNode = $currentNode->next; } } } public function insertAfter(string $data = NULL, string $query = NULL) { $newNode = new ListNode($data); if ($this->_firstNode) { $nextNode = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { if ($nextNode !== NULL) { $newNode->next = $nextNode; } $currentNode->next = $newNode; $this->_totalNode++; break; } $currentNode = $currentNode->next; $nextNode = $currentNode->next; } } } public function deleteFirst() { if ($this->_firstNode !== NULL) { if ($this->_firstNode->next !== NULL) { $this->_firstNode = $this->_firstNode->next; } else { $this->_firstNode = NULL; } $this->_totalNode--; return TRUE; } return FALSE; } public function deleteLast() { if ($this->_firstNode !== NULL) { $currentNode = $this->_firstNode; if ($currentNode->next === NULL) { $this->_firstNode = NULL; } else { $previousNode = NULL; while ($currentNode->next !== NULL) { $previousNode = $currentNode; $currentNode = $currentNode->next; } $previousNode->next = NULL; $this->_totalNode--; return TRUE; } } return FALSE; } public function delete(string $query = NULL) { if ($this->_firstNode) { $previous = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { if ($currentNode->next === NULL) { $previous->next = NULL; } else { $previous->next = $currentNode->next; } $this->_totalNode--; break; } $previous = $currentNode; $currentNode = $currentNode->next; } } } public function reverse() { if ($this->_firstNode !== NULL) { if ($this->_firstNode->next !== NULL) { $reversedList = NULL; $next = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { $next = $currentNode->next; $currentNode->next = $reversedList; $reversedList = $currentNode; $currentNode = $next; } $this->_firstNode = $reversedList; } } } public function getNthNode(int $n = 0) { $count = 1; if ($this->_firstNode !== NULL && $n <= $this->_totalNode) { $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($count === $n) { return $currentNode; } $count++; $currentNode = $currentNode->next; } } } public function display() { echo "Total book titles: " . $this->_totalNode . "\n"; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { echo $currentNode->data . "\n"; $currentNode = $currentNode->next; } } public function getSize() { return $this->_totalNode; } public function current() { return $this->_currentNode->data; } public function next() { $this->_currentPosition++; $this->_currentNode = $this->_currentNode->next; } public function key() { return $this->_currentPosition; } public function rewind() { $this->_currentPosition = 0; $this->_currentNode = $this->_firstNode; } public function valid() { return $this->_currentNode !== NULL; } } class DeQueue { private $limit; private $queue; public function __construct(int $limit = 20) { $this->limit = $limit; $this->queue = new LinkedList(); } public function dequeueFromFront(): string { if ($this->isEmpty()) { throw new UnderflowException('Queue is empty'); } else { $lastItem = $this->peekFront(); $this->queue->deleteFirst(); return $lastItem; } } public function dequeueFromBack(): string { if ($this->isEmpty()) { throw new UnderflowException('Queue is empty'); } else { $lastItem = $this->peekBack(); $this->queue->deleteLast(); return $lastItem; } } public function enqueueAtBack(string $newItem) { if ($this->queue->getSize() < $this->limit) { $this->queue->insert($newItem); } else { throw new OverflowException('Queue is full'); } } public function enqueueAtFront(string $newItem) { if ($this->queue->getSize() < $this->limit) { $this->queue->insertAtFirst($newItem); } else { throw new OverflowException('Queue is full'); } } public function peekFront(): string { return $this->queue->getNthNode(1)->data; } public function peekBack(): string { return $this->queue->getNthNode($this->queue->getSize())->data; } public function isEmpty(): bool { return $this->queue->getSize() == 0; } } try { $agents = new DeQueue(10); $agents->enqueueAtFront("Fred"); $agents->enqueueAtFront("John"); $agents->enqueueAtBack("Keith"); $agents->enqueueAtBack("Adiyan"); $agents->enqueueAtFront("Mikhael"); echo $agents->dequeueFromBack() . "\n"; echo $agents->dequeueFromFront() . "\n"; echo $agents->peekFront() . "\n"; } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/9.php
Chapter04/9.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class MyPQ extends SplPriorityQueue { public function compare($priority1, $priority2) { return $priority1 <=> $priority2; } } $agents = new MyPQ(); $agents->insert("Fred", 1); $agents->insert("John", 2); $agents->insert("Keith", 3); $agents->insert("Adiyan", 4); $agents->insert("Mikhael", 2); //mode of extraction $agents->setExtractFlags(MyPQ::EXTR_BOTH); //Go to TOP $agents->top(); while ($agents->valid()) { $current = $agents->current(); echo $current['data'] . "\n"; $agents->next(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/7.php
Chapter04/7.php
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $agents = new SplQueue(); $agents->enqueue("Fred"); $agents->enqueue("John"); $agents->enqueue("Keith"); $agents->enqueue("Adiyan"); $agents->enqueue("Mikhael"); echo $agents->dequeue()."\n"; echo $agents->dequeue()."\n"; echo $agents->bottom()."\n";
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/10.php
Chapter04/10.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ interface Queue { public function enqueue(string $item); public function dequeue(); public function peek(); public function isEmpty(); } class CircularQueue implements Queue { private $queue; private $limit; private $front = 0; private $rear = 0; public function __construct(int $limit = 5) { $this->limit = $limit; $this->queue = []; } public function size() { if ($this->rear > $this->front) return $this->rear - $this->front; return $this->limit - $this->front + $this->rear; } public function isEmpty() { return $this->rear == $this->front; } public function isFull() { $diff = $this->rear - $this->front; if ($diff == -1 || $diff == ($this->limit - 1)) return true; return false; } public function enqueue(string $item) { if ($this->isFull()) { throw new OverflowException("Queue is Full."); } else { $this->queue[$this->rear] = $item; $this->rear = ($this->rear + 1) % $this->limit; } } public function dequeue() { $item = ""; if ($this->isEmpty()) { throw new UnderflowException("Queue is empty"); } else { $item = $this->queue[$this->front]; $this->queue[$this->front] = NULL; $this->front = ($this->front + 1) % $this->limit; } return $item; } public function peek() { return $this->queue[$this->front]; } } try { $cq = new CircularQueue; $cq->enqueue("One"); $cq->enqueue("Two"); $cq->enqueue("Three"); $cq->enqueue("Four"); $cq->dequeue(); $cq->enqueue("Five"); echo $cq->size(); } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/5.php
Chapter04/5.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ interface Queue { public function enqueue(string $item); public function dequeue(); public function peek(); public function isEmpty(); } class AgentQueue implements Queue { private $limit; private $queue; public function __construct(int $limit = 20) { $this->limit = $limit; $this->queue = []; } public function dequeue(): string { if ($this->isEmpty()) { throw new UnderflowException('Queue is empty'); } else { return array_shift($this->queue); } } public function enqueue(string $newItem) { if (count($this->queue) < $this->limit) { array_push($this->queue, $newItem); } else { throw new OverflowException('Queue is full'); } } public function peek(): string { return current($this->queue); } public function isEmpty(): bool { return empty($this->queue); } } try { $agents = new AgentQueue(10); $agents->enqueue("Fred"); $agents->enqueue("John"); $agents->enqueue("Keith"); $agents->enqueue("Adiyan"); $agents->enqueue("Mikhael"); echo $agents->dequeue()."\n"; echo $agents->dequeue()."\n"; echo $agents->peek()."\n"; } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/3.php
Chapter04/3.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $books = new SplStack(); $books->push("Introduction to PHP7"); $books->push("Mastering JavaScript"); $books->push("MySQL Workbench tutorial"); echo $books->pop() . "\n"; echo $books->top() . "\n";
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/1.php
Chapter04/1.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ interface Stack { public function push(string $item); public function pop(); public function top(); public function isEmpty(); } class Books implements Stack { private $limit; private $stack; public function __construct(int $limit = 20) { $this->limit = $limit; $this->stack = []; } public function pop(): string { if ($this->isEmpty()) { throw new UnderflowException('Stack is empty'); } else { return array_pop($this->stack); } } public function push(string $newItem) { if (count($this->stack) < $this->limit) { array_push($this->stack, $newItem); } else { throw new OverflowException('Stack is full'); } } public function top(): string { return end($this->stack); } public function isEmpty(): bool { return empty($this->stack); } } try { $programmingBooks = new Books(10); $programmingBooks->push("Introduction to PHP7"); $programmingBooks->push("Mastering JavaScript"); $programmingBooks->push("MySQL Workbench tutorial"); echo $programmingBooks->pop()."\n"; echo $programmingBooks->top()."\n"; } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter04/2.php
Chapter04/2.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class ListNode { public $data = NULL; public $next = NULL; public function __construct(string $data = NULL) { $this->data = $data; } } class LinkedList implements Iterator { private $_firstNode = NULL; private $_totalNode = 0; private $_currentNode = NULL; private $_currentPosition = 0; public function insert(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; } else { $currentNode = $this->_firstNode; while ($currentNode->next !== NULL) { $currentNode = $currentNode->next; } $currentNode->next = $newNode; } $this->_totalNode++; return TRUE; } public function insertAtFirst(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; } else { $currentFirstNode = $this->_firstNode; $this->_firstNode = &$newNode; $newNode->next = $currentFirstNode; } $this->_totalNode++; return TRUE; } public function search(string $data = NULL) { if ($this->_totalNode) { $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $data) { return $currentNode; } $currentNode = $currentNode->next; } } return FALSE; } public function insertBefore(string $data = NULL, string $query = NULL) { $newNode = new ListNode($data); if ($this->_firstNode) { $previous = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { $newNode->next = $currentNode; $previous->next = $newNode; $this->_totalNode++; break; } $previous = $currentNode; $currentNode = $currentNode->next; } } } public function insertAfter(string $data = NULL, string $query = NULL) { $newNode = new ListNode($data); if ($this->_firstNode) { $nextNode = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { if ($nextNode !== NULL) { $newNode->next = $nextNode; } $currentNode->next = $newNode; $this->_totalNode++; break; } $currentNode = $currentNode->next; $nextNode = $currentNode->next; } } } public function deleteFirst() { if ($this->_firstNode !== NULL) { if ($this->_firstNode->next !== NULL) { $this->_firstNode = $this->_firstNode->next; } else { $this->_firstNode = NULL; } $this->_totalNode--; return TRUE; } return FALSE; } public function deleteLast() { if ($this->_firstNode !== NULL) { $currentNode = $this->_firstNode; if ($currentNode->next === NULL) { $this->_firstNode = NULL; } else { $previousNode = NULL; while ($currentNode->next !== NULL) { $previousNode = $currentNode; $currentNode = $currentNode->next; } $previousNode->next = NULL; $this->_totalNode--; return TRUE; } } return FALSE; } public function delete(string $query = NULL) { if ($this->_firstNode) { $previous = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { if ($currentNode->next === NULL) { $previous->next = NULL; } else { $previous->next = $currentNode->next; } $this->_totalNode--; break; } $previous = $currentNode; $currentNode = $currentNode->next; } } } public function reverse() { if ($this->_firstNode !== NULL) { if ($this->_firstNode->next !== NULL) { $reversedList = NULL; $next = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { $next = $currentNode->next; $currentNode->next = $reversedList; $reversedList = $currentNode; $currentNode = $next; } $this->_firstNode = $reversedList; } } } public function getNthNode(int $n = 0) { $count = 1; if ($this->_firstNode !== NULL && $n <= $this->_totalNode) { $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($count === $n) { return $currentNode; } $count++; $currentNode = $currentNode->next; } } } public function display() { echo "Total book titles: " . $this->_totalNode . "\n"; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { echo $currentNode->data . "\n"; $currentNode = $currentNode->next; } } public function getSize() { return $this->_totalNode; } public function current() { return $this->_currentNode->data; } public function next() { $this->_currentPosition++; $this->_currentNode = $this->_currentNode->next; } public function key() { return $this->_currentPosition; } public function rewind() { $this->_currentPosition = 0; $this->_currentNode = $this->_firstNode; } public function valid() { return $this->_currentNode !== NULL; } } interface Stack { public function push(string $item); public function pop(); public function top(); public function isEmpty(); } class BookList implements Stack { private $stack; public function __construct() { $this->stack = new LinkedList(); } public function pop(): string { if ($this->isEmpty()) { throw new UnderflowException('Stack is empty'); } else { $lastItem = $this->top(); $this->stack->deleteLast(); return $lastItem; } } public function push(string $newItem) { $this->stack->insert($newItem); } public function top(): string { return $this->stack->getNthNode($this->stack->getSize())->data; } public function isEmpty(): bool { return $this->stack->getSize() == 0; } } try { $programmingBooks = new BookList(); $programmingBooks->push("Introduction to PHP7"); $programmingBooks->push("Mastering JavaScript"); $programmingBooks->push("MySQL Workbench tutorial"); echo $programmingBooks->pop()."\n"; echo $programmingBooks->pop()."\n"; echo $programmingBooks->top()."\n"; } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter06/4.php
Chapter06/4.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class Node { public $data; public $left; public $right; public function __construct(int $data = NULL) { $this->data = $data; $this->left = NULL; $this->right = NULL; } public function min() { $node = $this; while($node->left) { $node = $node->left; } return $node; } public function max() { $node = $this; while($node->right) { $node = $node->right; } return $node; } public function successor() { $node = $this; if($node->right) return $node->right->min(); else return NULL; } public function predecessor() { $node = $this; if($node->left) return $node->left->max(); else return NULL; } } class BST { public $root = NULL; public function __construct(int $data) { $this->root = new Node($data); } public function isEmpty(): bool { return $this->root === NULL; } public function search(int $data) { if ($this->isEmpty()) { return FALSE; } $node = $this->root; while ($node) { if ($data > $node->data) { $node = $node->right; } elseif ($data < $node->data) { $node = $node->left; } else { break; } } return $node; } public function insert(int $data) { if($this->isEmpty()) { $node = new Node($data); $this->root = $node; return $node; } $node = $this->root; while($node) { if($data > $node->data) { if($node->right) { $node = $node->right; } else { $node->right = new Node($data); $node = $node->right; break; } } elseif($data < $node->data) { if($node->left) { $node = $node->left; } else { $node->left = new Node($data); $node = $node->left; break; } } else { break; } } return $node; } public function traverse(Node $node) { if ($node) { if ($node->left) $this->traverse($node->left); echo $node->data . "\n"; if ($node->right) $this->traverse($node->right); } } } try { $tree = new BST(10); $tree->insert(12); $tree->insert(6); $tree->insert(3); $tree->insert(8); $tree->insert(15); $tree->insert(13); $tree->insert(36); echo $tree->search(14) ? "Found" : "Not Found"; echo "\n"; echo $tree->search(36) ? "Found" : "Not Found"; $tree->traverse($tree->root); echo $tree->root->predecessor()->data; } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter06/6.php
Chapter06/6.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class Node { public $data; public $left; public $right; public $parent; public function __construct(int $data = NULL, Node $parent = NULL) { $this->data = $data; $this->parent = $parent; $this->left = NULL; $this->right = NULL; } public function min() { $node = $this; while($node->left) { $node = $node->left; } return $node; } public function max() { $node = $this; while($node->right) { $node = $node->right; } return $node; } public function successor() { $node = $this; if($node->right) return $node->right->min(); else return NULL; } public function predecessor() { $node = $this; if($node->left) return $node->left->max(); else return NULL; } public function delete() { $node = $this; if (!$node->left && !$node->right) { if ($node->parent->left === $node) { $node->parent->left = NULL; } else { $node->parent->right = NULL; } } elseif ($node->left && $node->right) { $successor = $node->successor(); $node->data = $successor->data; $successor->delete(); } elseif ($node->left) { if ($node->parent->left === $node) { $node->parent->left = $node->left; $node->left->parent = $node->parent->left; } else { $node->parent->right = $node->left; $node->left->parent = $node->parent->right; } $node->left = NULL; } elseif ($node->right) { if ($node->parent->left === $node) { $node->parent->left = $node->right; $node->right->parent = $node->parent->left; } else { $node->parent->right = $node->right; $node->right->parent = $node->parent->right; } $node->right = NULL; } } } class BST { public $root = NULL; public function __construct(int $data) { $this->root = new Node($data); } public function isEmpty(): bool { return $this->root === NULL; } public function remove(int $data) { $node = $this->search($data); if($node) $node->delete(); } public function search(int $data) { if ($this->isEmpty()) { return FALSE; } $node = $this->root; while ($node) { if ($data > $node->data) { $node = $node->right; } elseif ($data < $node->data) { $node = $node->left; } else { break; } } return $node; } public function insert(int $data) { if($this->isEmpty()) { $node = new Node($data); $this->root = $node; return $node; } $node = $this->root; while($node) { if($data > $node->data) { if($node->right) { $node = $node->right; } else { $node->right = new Node($data, $node); $node = $node->right; break; } } elseif($data < $node->data) { if($node->left) { $node = $node->left; } else { $node->left = new Node($data, $node); $node = $node->left; break; } } else { break; } } return $node; } public function traverse(Node $node, string $type="in-order") { switch($type) { case "in-order": $this->inOrder($node); break; case "pre-order": $this->preOrder($node); break; case "post-order": $this->postOrder($node); break; } } public function preOrder(Node $node) { if ($node) { echo $node->data . " "; if ($node->left) $this->traverse($node->left); if ($node->right) $this->traverse($node->right); } } public function inOrder(Node $node) { if ($node) { if ($node->left) $this->traverse($node->left); echo $node->data . " "; if ($node->right) $this->traverse($node->right); } } public function postOrder(Node $node) { if ($node) { if ($node->left) $this->traverse($node->left); if ($node->right) $this->traverse($node->right); echo $node->data . " "; } } } try { $tree = new BST(10); $tree->insert(12); $tree->insert(6); $tree->insert(3); $tree->insert(8); $tree->insert(15); $tree->insert(13); $tree->insert(36); $tree->traverse($tree->root, 'pre-order'); echo "\n"; $tree->traverse($tree->root, 'in-order'); echo "\n"; $tree->traverse($tree->root, 'post-order'); } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter06/5.php
Chapter06/5.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class Node { public $data; public $left; public $right; public $parent; public function __construct(int $data = NULL, Node $parent = NULL) { $this->data = $data; $this->parent = $parent; $this->left = NULL; $this->right = NULL; } public function min() { $node = $this; while($node->left) { $node = $node->left; } return $node; } public function max() { $node = $this; while($node->right) { $node = $node->right; } return $node; } public function successor() { $node = $this; if($node->right) return $node->right->min(); else return NULL; } public function predecessor() { $node = $this; if($node->left) return $node->left->max(); else return NULL; } public function delete() { $node = $this; if (!$node->left && !$node->right) { if ($node->parent->left === $node) { $node->parent->left = NULL; } else { $node->parent->right = NULL; } } elseif ($node->left && $node->right) { $successor = $node->successor(); $node->data = $successor->data; $successor->delete(); } elseif ($node->left) { if ($node->parent->left === $node) { $node->parent->left = $node->left; $node->left->parent = $node->parent->left; } else { $node->parent->right = $node->left; $node->left->parent = $node->parent->right; } $node->left = NULL; } elseif ($node->right) { if ($node->parent->left === $node) { $node->parent->left = $node->right; $node->right->parent = $node->parent->left; } else { $node->parent->right = $node->right; $node->right->parent = $node->parent->right; } $node->right = NULL; } } } class BST { public $root = NULL; public function __construct(int $data) { $this->root = new Node($data); } public function isEmpty(): bool { return $this->root === NULL; } public function remove(int $data) { $node = $this->search($data); if($node) $node->delete(); } public function search(int $data) { if ($this->isEmpty()) { return FALSE; } $node = $this->root; while ($node) { if ($data > $node->data) { $node = $node->right; } elseif ($data < $node->data) { $node = $node->left; } else { break; } } return $node; } public function insert(int $data) { if($this->isEmpty()) { $node = new Node($data); $this->root = $node; return $node; } $node = $this->root; while($node) { if($data > $node->data) { if($node->right) { $node = $node->right; } else { $node->right = new Node($data, $node); $node = $node->right; break; } } elseif($data < $node->data) { if($node->left) { $node = $node->left; } else { $node->left = new Node($data, $node); $node = $node->left; break; } } else { break; } } return $node; } public function traverse(Node $node) { if ($node) { if ($node->left) $this->traverse($node->left); echo $node->data . "\n"; if ($node->right) $this->traverse($node->right); } } } try { $tree = new BST(10); $tree->insert(12); $tree->insert(6); $tree->insert(3); $tree->insert(8); $tree->insert(15); $tree->insert(13); $tree->insert(36); $tree->traverse($tree->root); $tree->remove(15); $tree->traverse($tree->root); } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter06/3.php
Chapter06/3.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class BinaryTree { public $nodes = []; public function __construct(Array $nodes) { $this->nodes = $nodes; } public function traverse(int $num = 0, int $level = 0) { if (isset($this->nodes[$num])) { echo str_repeat("-", $level); echo $this->nodes[$num] . "\n"; $this->traverse(2 * $num + 1, $level+1); $this->traverse(2 * ($num + 1), $level+1); } } } try { $nodes = []; $nodes[] = "Final"; $nodes[] = "Semi Final 1"; $nodes[] = "Semi Final 2"; $nodes[] = "Quarter Final 1"; $nodes[] = "Quarter Final 2"; $nodes[] = "Quarter Final 3"; $nodes[] = "Quarter Final 4"; $tree = new BinaryTree($nodes); $tree->traverse(0); } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter06/1.php
Chapter06/1.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class TreeNode { public $data = NULL; public $children = []; public function __construct(string $data = NULL) { $this->data = $data; } public function addChildren(TreeNode $node) { $this->children[] = $node; } } class Tree { public $root = NULL; public function __construct(TreeNode $node) { $this->root = $node; } public function traverse(TreeNode $node, int $level = 0) { if ($node) { echo str_repeat("-", $level); echo $node->data . "\n"; foreach ($node->children as $childNode) { $this->traverse($childNode, $level + 1); } } } } try { $ceo = new TreeNode("CEO"); $tree = new Tree($ceo); $cto = new TreeNode("CTO"); $cfo = new TreeNode("CFO"); $cmo = new TreeNode("CMO"); $coo = new TreeNode("COO"); $ceo->addChildren($cto); $ceo->addChildren($cfo); $ceo->addChildren($cmo); $ceo->addChildren($coo); $seniorArchitect = new TreeNode("Senior Architect"); $softwareEngineer = new TreeNode("Software Engineer"); $userInterfaceDesigner = new TreeNode("User Interface Designer"); $qualityAssuranceEngineer = new TreeNode("Quality Assurance Engineer"); $cto->addChildren($seniorArchitect); $seniorArchitect->addChildren($softwareEngineer); $cto->addChildren($qualityAssuranceEngineer); $cto->addChildren($userInterfaceDesigner); $tree->traverse($tree->root); } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter06/2.php
Chapter06/2.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class BinaryNode { public $data; public $left; public $right; public function __construct(string $data = NULL) { $this->data = $data; $this->left = NULL; $this->right = NULL; } public function addChildren(BinaryNode $left, BinaryNode $right) { $this->left = $left; $this->right = $right; } } class BinaryTree { public $root = NULL; public function __construct(BinaryNode $node) { $this->root = $node; } public function isEmpty(): bool { return $this->root === NULL; } public function traverse(BinaryNode $node, int $level = 0) { if ($node) { echo str_repeat("-", $level); echo $node->data . "\n"; if ($node->left) $this->traverse($node->left, $level + 1); if ($node->right) $this->traverse($node->right, $level + 1); } } } try { $final = new BinaryNode("Final"); $tree = new BinaryTree($final); $semiFinal1 = new BinaryNode("Semi Final 1"); $semiFinal2 = new BinaryNode("Semi Final 2"); $quarterFinal1 = new BinaryNode("Quarter Final 1"); $quarterFinal2 = new BinaryNode("Quarter Final 2"); $quarterFinal3 = new BinaryNode("Quarter Final 3"); $quarterFinal4 = new BinaryNode("Quarter Final 4"); $semiFinal1->addChildren($quarterFinal1, $quarterFinal2); $semiFinal2->addChildren($quarterFinal3, $quarterFinal4); $final->addChildren($semiFinal1, $semiFinal2); $tree->traverse($tree->root); } catch (Exception $e) { echo $e->getMessage(); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter02/1.php
Chapter02/1.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $array = [1,2,3,4,5]; $mixedArray = []; $mixedArray[0] = 200; $mixedArray['name'] = "Mixed array"; $mixedArray[1] = 10.65; $mixedArray[2] = ['I', 'am', 'another', 'array']; $array = [10,20,30,40,50]; $array[] = 70; $array[] = 80; $arraySize = count($array); for($i = 0;$i<$arraySize;$i++) { echo "Position ".$i." holds the value ".$array[$i]."\n"; } $startMemory = memory_get_usage(); $array = []; $array[10] = 100; $array[21] = 200; $array[29] = 300; $array[500] = 1000; $array[1001] = 10000; $array[71] = 1971; foreach($array as $index => $value) { echo "Position ".$index." holds the value ".$value."\n"; } echo memory_get_usage() - $startMemory, " bytes\n"; $studentInfo = []; $studentInfo['Name'] = "Adiyan"; $studentInfo['Age'] = 11; $studentInfo['Class'] = 6; $studentInfo['RollNumber'] = 71; $studentInfo['Contact'] = "info@adiyan.com"; foreach($studentInfo as $key => $value) { echo $key.": ".$value."\n"; } $players = []; $players[] = ['Name' => "Ronaldo", "Age" => 31, "Country" => "Portugal", "Team" => "Real Madrid"]; $players[] = ['Name' => "Messi", "Age" => 27, "Country" => "Argentina", "Team" => "Barcelona"]; $players[] = ['Name' => "Neymar", "Age" => 24, "Country" => "Brazil", "Team" => "Barcelona"]; $players[] = ['Name' => "Rooney", "Age" => 30, "Country" => "England", "Team" => "Man United"]; foreach($players as $index => $playerInfo) { echo "Info of player # ".($index+1)."\n"; foreach($playerInfo as $key => $value) { echo $key.": ".$value."\n"; } echo "\n"; } $startTime = microtime(); $startMemory = memory_get_usage(); $array = []; // new SplFixedArray(10000); //$array = range(1, 100000); for($i = 0;$i<10000;$i++) $array[$i] = $i; echo memory_get_usage() - $startMemory, ' bytes'; echo "\n".microtime() - $startTime, ' nano second'; $graph = []; $nodes = ['A', 'B', 'C', 'D', 'E']; foreach ($nodes as $xNode) { foreach ($nodes as $yNode) { $graph[$xNode][$yNode] = 0; } } $graph["A"]["B"] = 1; $graph["B"]["A"] = 1; $graph["A"]["C"] = 1; $graph["C"]["A"] = 1; $graph["A"]["E"] = 1; $graph["E"]["A"] = 1; $graph["B"]["E"] = 1; $graph["E"]["B"] = 1; $graph["B"]["D"] = 1; $graph["D"]["B"] = 1; foreach ($nodes as $xNode) { foreach ($nodes as $yNode) { echo $graph[$xNode][$yNode] . "\t"; } echo "\n"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter02/2.php
Chapter02/2.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $startMemory = memory_get_usage(); $array = new SplFixedArray(100); for ($i = 0; $i < 100; $i++) $array[$i] = new SplFixedArray(100); echo memory_get_usage() - $startMemory, ' bytes'; $startMemory = memory_get_usage(); $array = range(1,100000); $endMemory = memory_get_usage(); echo ($endMemory - $startMemory)." bytes"; $items = 100000; $startTime = microtime(); $startMemory = memory_get_usage(); $array = new SplFixedArray($items); for ($i = 0; $i < $items; $i++) { $array[$i] = $i; } echo array_filter($array); $endMemory = memory_get_usage(); $endTime = microtime(); $memoryConsumed = ($endMemory - $startMemory) / (1024 * 1024); $memoryConsumed = ceil($memoryConsumed); echo "memory = {$memoryConsumed} MB\n"; echo "time =".($endTime-$startTime)."\n"; $array =[1 => 10, 2 => 100, 3 => 1000, 4 => 10000]; $splArray = SplFixedArray::fromArray($array,false); unset($array); print_r($splArray); $keyArray = [1 => 10, 2 => 100, 3 => 1000, 4 => 10000]; $splArray = SplFixedArray::fromArray($keyArray, $keyArray); unset($array); print_r($splArray); $items = 5; $array = new SplFixedArray($items); for ($i = 0; $i < $items; $i++) { $array[$i] = $i * 10; } $newArray = $array->toArray(); print_r($newArray); $items = 5; $array = new SplFixedArray($items); for ($i = 0; $i < $items; $i++) { $array[$i] = $i * 10; } $array->setSize(10); $array[7] = 100; $array = []; $array['Germany'] = "Position 1"; $array['Argentina'] = "Position 2"; $array['Portugal'] = "Position 6"; $array['Fifa_World_Cup'] = "2018 Russia"; $ronaldo = [ "name" => "Ronaldo", "country" => "Portugal", "age" => 31, "currentTeam" => "Real Madrid" ]; $messi = [ "name" => "Messi", "country" => "Argentina", "age" => 27, "currentTeam" => "Barcelona" ]; $team = [ "player1" => $ronaldo, "player2" => $messi ]; Class Player { public $name; public $country; public $age; public $currentTeam; } $ronaldo = new Player; $ronaldo->name = "Ronaldo"; $ronaldo->country = "Portugal"; $ronaldo->age = 31; $ronaldo->currentTeam = "Real Madrid"; $odd = []; $odd[] = 1; $odd[] = 3; $odd[] = 5; $odd[] = 7; $odd[] = 9; $prime = []; $prime[] = 2; $prime[] = 3; $prime[] = 5; if (in_array(2, $prime)) { echo "2 is a prime"; } $union = array_merge($prime, $odd); $intersection = array_intersect($prime, $odd); $compliment = array_diff($prime, $odd); $odd = []; $odd[1] = true; $odd[3] = true; $odd[5] = true; $odd[7] = true; $odd[9] = true; $prime = []; $prime[2] = true; $prime[3] = true; $prime[5] = true; if (isset($prime[2])) { echo "2 is a prime"; } $union = $prime + $odd; $intersection = array_intersect_key($prime, $odd); $compliment = array_diff_key($prime, $odd);
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/4.php
Chapter13/4.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ require __DIR__ . '/vendor/autoload.php'; use Tarsana\Functional as F; $queue = []; $enqueue = F\append(F\__(), F\__()); $head = F\head(F\__()); $dequeue = F\tail(F\__()); $queue = $enqueue(1, $queue); $queue = $enqueue(2, $queue); $queue = $enqueue(3, $queue); echo "Queue is ".F\toString($queue)."\n"; $item = $head($queue); $queue = $dequeue($queue); echo "Dequeue-ed item: ".$item."\n"; echo "Queue is ".F\toString($queue)."\n"; $queue = $enqueue(4, $queue); echo "Queue is ".F\toString($queue)."\n";
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/5.php
Chapter13/5.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function treeTraverse(array &$tree, int $index = 0, int $level = 0, &$outputStr = "") : ?bool { if(isset($tree[$index])) { $outputStr .= str_repeat("-", $level); $outputStr .= $tree[$index] . "\n"; treeTraverse($tree, 2 * $index + 1, $level+1,$outputStr); treeTraverse($tree, 2 * ($index + 1), $level+1,$outputStr); } else { return false; } return null; } $nodes = []; $nodes[] = "Final"; $nodes[] = "Semi Final 1"; $nodes[] = "Semi Final 2"; $nodes[] = "Quarter Final 1"; $nodes[] = "Quarter Final 2"; $nodes[] = "Quarter Final 3"; $nodes[] = "Quarter Final 4"; $treeStr = ""; treeTraverse($nodes,0,0,$treeStr); echo $treeStr;
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/3.php
Chapter13/3.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ require __DIR__ . '/vendor/autoload.php'; use Tarsana\Functional as F; $stack = []; $push = F\append(F\__(), F\__()); $top = F\last(F\__()); $pop = F\init(F\__()); $stack = $push(1, $stack); $stack = $push(2, $stack); $stack = $push(3, $stack); echo "Stack is ".F\toString($stack)."\n"; $item = $top($stack); $stack = $pop($stack); echo "Pop-ed item: ".$item."\n"; echo "Stack is ".F\toString($stack)."\n"; $stack = $push(4, $stack); echo "Stack is ".F\toString($stack)."\n";
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/1.php
Chapter13/1.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $languages = ["php", "python", "java", "c", "erlang"]; foreach ($languages as $ind => $language) { $languages[$ind] = ucfirst($language); } $languages = array_map('ucfirst', $languages); function sum($a, $b, $c) { return $a + $b + $c; } function currySum($a) { return function($b) use ($a) { return function ($c) use ($a, $b) { return $a + $b + $c; }; }; } $sum = currySum(10)(20)(30); echo $sum; function partial($funcName, ...$args) { return function(...$innerArgs) use ($funcName, $args) { $allArgs = array_merge($args, $innerArgs); return call_user_func_array($funcName, $allArgs); }; } $sum = partial("sum", 10, 20); $sum = $sum(30); echo $sum;
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/2.php
Chapter13/2.php
<?php /** * Created by PhpStorm. * User: mizan * Date: 25/04/17 * Time: 10:58 AM */ require __DIR__ . '/vendor/autoload.php'; use Tarsana\Functional as F; $add = F\curry(function($x, $y, $z) { return $x + $y + $z; }); echo $add(1, 2, 4)."\n"; $addFive = $add(5); $addSix = $addFive(6); echo $addSix(2); $reduce = F\curry('array_reduce'); $sum = $reduce(F\__(), F\plus()); echo $sum([1, 2, 3, 4, 5], 0); $square = function($x) { return $x * $x; }; $addThenSquare = F\pipe(F\plus(), $square); echo $addThenSquare(2, 3);
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/vendor/autoload.php
Chapter13/vendor/autoload.php
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInit162d5f8ec26d0f35f7a435b58f506e91::getLoader();
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/vendor/composer/autoload_files.php
Chapter13/vendor/composer/autoload_files.php
<?php // autoload_files.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'ad301e9d734a656b3a7e0cfda5d86814' => $vendorDir . '/tarsana/functional/src/Internal/_functions.php', '074162fde8cc05bb516fe2da4bdde1e2' => $vendorDir . '/tarsana/functional/src/Internal/_stream.php', 'e49490e34f69c2b5dc378287aff873a3' => $vendorDir . '/tarsana/functional/src/functions.php', '86e6e0fbb8e27bd3acbcdbc4203d813e' => $vendorDir . '/tarsana/functional/src/operators.php', 'a32120ba94fa97a51d3028c3c72c6a2c' => $vendorDir . '/tarsana/functional/src/common.php', '828e32b012c9305974510428dface37d' => $vendorDir . '/tarsana/functional/src/object.php', '2f4f606cc5bf2a20346afa245643e51c' => $vendorDir . '/tarsana/functional/src/string.php', '67815361e2d72888c0507e858ef42a16' => $vendorDir . '/tarsana/functional/src/list.php', 'cffc2f002a7818ea4be857a6cb09c019' => $vendorDir . '/tarsana/functional/src/math.php', );
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/vendor/composer/autoload_real.php
Chapter13/vendor/composer/autoload_real.php
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit162d5f8ec26d0f35f7a435b58f506e91 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInit162d5f8ec26d0f35f7a435b58f506e91', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInit162d5f8ec26d0f35f7a435b58f506e91', 'loadClassLoader')); $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); if ($useStaticLoader) { require_once __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit162d5f8ec26d0f35f7a435b58f506e91::getInitializer($loader)); } else { $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } } $loader->register(true); if ($useStaticLoader) { $includeFiles = Composer\Autoload\ComposerStaticInit162d5f8ec26d0f35f7a435b58f506e91::$files; } else { $includeFiles = require __DIR__ . '/autoload_files.php'; } foreach ($includeFiles as $fileIdentifier => $file) { composerRequire162d5f8ec26d0f35f7a435b58f506e91($fileIdentifier, $file); } return $loader; } } function composerRequire162d5f8ec26d0f35f7a435b58f506e91($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { require $file; $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; } }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/vendor/composer/autoload_namespaces.php
Chapter13/vendor/composer/autoload_namespaces.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( );
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/vendor/composer/autoload_psr4.php
Chapter13/vendor/composer/autoload_psr4.php
<?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'Tarsana\\UnitTests\\Functional\\' => array($vendorDir . '/tarsana/functional/tests'), 'Tarsana\\Functional\\' => array($vendorDir . '/tarsana/functional/src/Classes'), );
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/vendor/composer/autoload_static.php
Chapter13/vendor/composer/autoload_static.php
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInit162d5f8ec26d0f35f7a435b58f506e91 { public static $files = array ( 'ad301e9d734a656b3a7e0cfda5d86814' => __DIR__ . '/..' . '/tarsana/functional/src/Internal/_functions.php', '074162fde8cc05bb516fe2da4bdde1e2' => __DIR__ . '/..' . '/tarsana/functional/src/Internal/_stream.php', 'e49490e34f69c2b5dc378287aff873a3' => __DIR__ . '/..' . '/tarsana/functional/src/functions.php', '86e6e0fbb8e27bd3acbcdbc4203d813e' => __DIR__ . '/..' . '/tarsana/functional/src/operators.php', 'a32120ba94fa97a51d3028c3c72c6a2c' => __DIR__ . '/..' . '/tarsana/functional/src/common.php', '828e32b012c9305974510428dface37d' => __DIR__ . '/..' . '/tarsana/functional/src/object.php', '2f4f606cc5bf2a20346afa245643e51c' => __DIR__ . '/..' . '/tarsana/functional/src/string.php', '67815361e2d72888c0507e858ef42a16' => __DIR__ . '/..' . '/tarsana/functional/src/list.php', 'cffc2f002a7818ea4be857a6cb09c019' => __DIR__ . '/..' . '/tarsana/functional/src/math.php', ); public static $prefixLengthsPsr4 = array ( 'T' => array ( 'Tarsana\\UnitTests\\Functional\\' => 29, 'Tarsana\\Functional\\' => 19, ), ); public static $prefixDirsPsr4 = array ( 'Tarsana\\UnitTests\\Functional\\' => array ( 0 => __DIR__ . '/..' . '/tarsana/functional/tests', ), 'Tarsana\\Functional\\' => array ( 0 => __DIR__ . '/..' . '/tarsana/functional/src/Classes', ), ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInit162d5f8ec26d0f35f7a435b58f506e91::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInit162d5f8ec26d0f35f7a435b58f506e91::$prefixDirsPsr4; }, null, ClassLoader::class); } }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/vendor/composer/ClassLoader.php
Chapter13/vendor/composer/ClassLoader.php
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. * * $loader = new \Composer\Autoload\ClassLoader(); * * // register classes with namespaces * $loader->add('Symfony\Component', __DIR__.'/component'); * $loader->add('Symfony', __DIR__.'/framework'); * * // activate the autoloader * $loader->register(); * * // to enable searching the include path (eg. for PEAR packages) * $loader->setUseIncludePath(true); * * In this example, if you try to use a class in the Symfony\Component * namespace or one of its children (Symfony\Component\Console for instance), * the autoloader will first look for the class under the component/ * directory, and it will then fallback to the framework/ directory if not * found before giving up. * * This class is loosely based on the Symfony UniversalClassLoader. * * @author Fabien Potencier <fabien@symfony.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @see http://www.php-fig.org/psr/psr-0/ * @see http://www.php-fig.org/psr/psr-4/ */ class ClassLoader { // PSR-4 private $prefixLengthsPsr4 = array(); private $prefixDirsPsr4 = array(); private $fallbackDirsPsr4 = array(); // PSR-0 private $prefixesPsr0 = array(); private $fallbackDirsPsr0 = array(); private $useIncludePath = false; private $classMap = array(); private $classMapAuthoritative = false; private $missingClasses = array(); private $apcuPrefix; public function getPrefixes() { if (!empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', $this->prefixesPsr0); } return array(); } public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } public function getFallbackDirs() { return $this->fallbackDirsPsr0; } public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } public function getClassMap() { return $this->classMap; } /** * @param array $classMap Class to filename map */ public function addClassMap(array $classMap) { if ($this->classMap) { $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } } /** * Registers a set of PSR-0 directories for a given prefix, either * appending or prepending to the ones previously set for this prefix. * * @param string $prefix The prefix * @param array|string $paths The PSR-0 root directories * @param bool $prepend Whether to prepend the directories */ public function add($prefix, $paths, $prepend = false) { if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( (array) $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, (array) $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = (array) $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( (array) $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], (array) $paths ); } } /** * Registers a set of PSR-4 directories for a given namespace, either * appending or prepending to the ones previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param array|string $paths The PSR-4 base directories * @param bool $prepend Whether to prepend the directories * * @throws \InvalidArgumentException */ public function addPsr4($prefix, $paths, $prepend = false) { if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( (array) $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, (array) $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( (array) $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], (array) $paths ); } } /** * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix. * * @param string $prefix The prefix * @param array|string $paths The PSR-0 base directories */ public function set($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; } } /** * Registers a set of PSR-4 directories for a given namespace, * replacing any others previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param array|string $paths The PSR-4 base directories * * @throws \InvalidArgumentException */ public function setPsr4($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } } /** * Turns on searching the include path for class files. * * @param bool $useIncludePath */ public function setUseIncludePath($useIncludePath) { $this->useIncludePath = $useIncludePath; } /** * Can be used to check if the autoloader uses the include path to check * for classes. * * @return bool */ public function getUseIncludePath() { return $this->useIncludePath; } /** * Turns off searching the prefix and fallback directories for classes * that have not been registered with the class map. * * @param bool $classMapAuthoritative */ public function setClassMapAuthoritative($classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Should class lookup fail if not found in the current class map? * * @return bool */ public function isClassMapAuthoritative() { return $this->classMapAuthoritative; } /** * APCu prefix to use to cache found/not-found classes, if the extension is enabled. * * @param string|null $apcuPrefix */ public function setApcuPrefix($apcuPrefix) { $this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null; } /** * The APCu prefix in use, or null if APCu caching is not enabled. * * @return string|null */ public function getApcuPrefix() { return $this->apcuPrefix; } /** * Registers this instance as an autoloader. * * @param bool $prepend Whether to prepend the autoloader or not */ public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); } /** * Unregisters this instance as an autoloader. */ public function unregister() { spl_autoload_unregister(array($this, 'loadClass')); } /** * Loads the given class or interface. * * @param string $class The name of the class * @return bool|null True if loaded, null otherwise */ public function loadClass($class) { if ($file = $this->findFile($class)) { includeFile($file); return true; } } /** * Finds the path to the file where the class is defined. * * @param string $class The name of the class * * @return string|false The path if found, false otherwise */ public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; } private function findFileWithExtension($class, $ext) { // PSR-4 lookup $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { $subPath = $class; while (false !== $lastPos = strrpos($subPath, '\\')) { $subPath = substr($subPath, 0, $lastPos); $search = $subPath.'\\'; if (isset($this->prefixDirsPsr4[$search])) { foreach ($this->prefixDirsPsr4[$search] as $dir) { $length = $this->prefixLengthsPsr4[$first][$search]; if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) { return $file; } } } } } // PSR-4 fallback dirs foreach ($this->fallbackDirsPsr4 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } // PSR-0 lookup if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); } else { // PEAR-like class name $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; } if (isset($this->prefixesPsr0[$first])) { foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } } } } // PSR-0 fallback dirs foreach ($this->fallbackDirsPsr0 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } // PSR-0 include paths. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } return false; } } /** * Scope isolated include. * * Prevents access to $this/self from included files. */ function includeFile($file) { include $file; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/vendor/composer/autoload_classmap.php
Chapter13/vendor/composer/autoload_classmap.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( );
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter13/vendor/tarsana/functional/build.php
Chapter13/vendor/tarsana/functional/build.php
<?php namespace Tarsana\Functional; /** * This script parses the source files using [dox](https://github.com/tj/dox) * and generates the unit tests and documentation files. */ require __DIR__ . '/vendor/autoload.php'; /** * Custom Types: * DoxBlock :: { * tags: [{ * type: String, * string: String, * types: [String], * name: String, * description: String * ... * }], * description: { * full: String, * summary: String, * body: String * }, * code: String, * ctx: { * type: String, * name: String, * ... * } * isPrivate: * isEvent: * isConstructor: * line: * ignore: * } * * Block :: { * type: file|function|class|method * name: String // DoxBlock.ctx.name * params: [{type: String, name: String}] * return: String * signatures: [String] * description: String * summary: String * internal: Boolean * ignore: Boolean * code: String * } * * Operation :: { * name: String, * signature: String * } * * Module :: { * path: String * name: String * docsPath: String * testsPath: String * blocks: [Block] * docs: String * tests: String * testsFooter: String * streamOperations: String * streamMethods: String * } */ /** * The entry point. * * @signature [String] -> IO * @param array $modules * @return void */ function build_main($modules) { build_init_stream_operations(); each(_f('build_module'), $modules); build_close_stream_operations(); } /** * Writes the header of the stream operations file. * * @signature IO * @return void */ function build_init_stream_operations() { file_put_contents( 'src/Internal/_stream_operations.php', "<?php\n\nuse Tarsana\Functional as F;\n\nreturn F\map(F\apply(F\_f('_stream_operation')), [\n\t['then', 'Function -> Any -> Any', F\_f('_stream_then')],\n" ); file_put_contents( 'docs/stream-operations.md', "# Stream Operations" ); } /** * Writes the footer of the stream operations file. * * @signature IO * @return void */ function build_close_stream_operations() { file_put_contents( 'src/Internal/_stream_operations.php', "\n]);\n", FILE_APPEND ); } /** * Extracts the modules files from composer.json. * * @signature [String] * @return array */ function get_modules() { $composer = json_decode(file_get_contents(__DIR__.'/composer.json')); return $composer->autoload->files; } /** * Generates unit tests and documentation for a module. * * @signature String -> IO * @param string $path * @return void */ function build_module($path) { apply(process_of([ 'module_of', 'generate_docs', 'generate_tests', 'generate_stream_operations', 'generate_stream_methods', 'write_module' ]), [$path]); } /** * Writes the module's docs and tests. * * @signature Module -> IO * @param object $module * @return void */ function write_module($module) { if ($module->docs) { $docsDir = dirname($module->docsPath); if (!is_dir($docsDir)) mkdir($docsDir, 0777, true); file_put_contents($module->docsPath, $module->docs); } if ($module->tests) { $testsDir = dirname($module->testsPath); if (!is_dir($testsDir)) mkdir($testsDir, 0777, true); file_put_contents($module->testsPath, $module->tests); } if ($module->streamOperations) { file_put_contents('src/Internal/_stream_operations.php', $module->streamOperations, FILE_APPEND); } if ($module->streamMethods) { file_put_contents('docs/stream-operations.md', $module->streamMethods, FILE_APPEND); } } /** * Creates a module from a path. * * @signature String -> Module * @param string $path * @return object */ function module_of($path) { return apply(process_of([ 'fill_name', 'fill_docs_path', 'fill_tests_path', 'fill_blocks' ]), [(object)['path' => $path]]); } /** * Fills the name of the Module based on the path. * 'src/xxx/aaa.php' -> 'aaa' * * @signature Module -> Module * @param object $module * @return object */ function fill_name($module) { $module->name = apply(pipe(split('/'), last(), split('.'), head()), [$module->path]); return $module; } /** * Fills documentation file path based on source file path. * 'src/xxx.php' -> 'docs/xxx.md' * * @signature Module -> Module * @param object $module * @return object */ function fill_docs_path($module) { $module->docsPath = replace(['src', '.php'], ['docs', '.md'], $module->path); return $module; } /** * Fills tests file path based on source file path. * 'src/xxx.php' -> 'tests/xxxTest.php' * * @signature Module -> Module * @param object $module * @return object */ function fill_tests_path($module) { $name = ucfirst(camelCase($module->name)); $dir = 'tests' . remove(3, dirname($module->path)); $module->testsPath = "{$dir}/{$name}Test.php"; return $module; } /** * Fills the blocks of the Module based on the path. * * @signature Module -> Module * @param array $module * @return array */ function fill_blocks($module) { $module->blocks = apply(pipe( prepend('dox -r < '), // "dox -r < src/...php" 'shell_exec', // "[{...}, ...]" 'json_decode', // [DoxBlock] map(_f('make_block')) // sort() ), [$module->path]); return $module; } /** * Converts a DoxBlock to a Block. * * @signature DoxBlock -> Block * @param object $doxBlock * @return object */ function make_block($doxBlock) { $tags = groupBy(get('name'), tags_of($doxBlock)); $type = 'function'; if (has('file', $tags)) $type = 'file'; if (has('class', $tags)) $type = 'class'; if (has('method', $tags)) $type = 'method'; $params = map(function($tag){ $parts = split(' ', get('value', $tag)); return [ 'type' => $parts[0], 'name' => $parts[1] ]; }, get('param', $tags) ?: []); $return = getPath(['return', 0, 'value'], $tags); $signatures = get('signature', $tags); if ($signatures) $signatures = map(get('value'), $signatures); return (object) [ 'type' => $type, 'name' => getPath(['ctx', 'name'], $doxBlock), 'params' => $params, 'return' => $return, 'signatures' => $signatures, 'description' => getPath(['description', 'full'], $doxBlock), 'summary' => getPath(['description', 'summary'], $doxBlock), 'internal' => has('internal', $tags), 'ignore' => has('ignore', $tags), 'stream' => has('stream', $tags) // 'code' => get('code', $doxBlock) ]; } /** * Returns an array of tags, each having a name and a value. * * @signature DoxBlock -> [{name: String, value: String}] * @param object $doxBlock * @return array */ function tags_of($doxBlock) { if ($doxBlock->tags) return map(function($tag){ return (object) [ 'name' => $tag->type, 'value' => $tag->string ]; }, $doxBlock->tags); return []; } /** * Generates documentation contents for a module. * * @signature Module -> Module * @param object $module * @return object */ function generate_docs($module) { $module->docs = ''; if (startsWith('_', $module->name)) return $module; return apply(process_of([ 'generate_docs_header', 'generate_docs_sommaire', 'generate_docs_contents' ]), [$module]); } /** * Generates documentation header. * * @signature Module -> Module * @param object $module * @return object */ function generate_docs_header($module) { $name = $module->name; $description = get('description', head($module->blocks)); $module->docs .= "# {$name}\n\n{$description}\n\n"; return $module; } /** * Generates documentation table of contents. * * @signature Module -> Module * @param object $module * @return object */ function generate_docs_sommaire($module) { $blocks = filter ( satisfiesAll(['ignore' => not(), 'internal' => not(), 'type' => equals('function')]), $module->blocks ); $items = map(_f('generate_docs_sommaire_item'), $blocks); $module->docs .= join('', $items); return $module; } /** * Generates an item of the documentation's table of contents. * * @signature Block -> String * @param object $block * @return string */ function generate_docs_sommaire_item($block) { $title = get('name', $block); $link = lowerCase($title); return "- [{$title}](#{$link}) - {$block->summary}\n\n"; } /** * Generates documentation contents. * * @signature Module -> Module * @param object $module * @return object */ function generate_docs_contents($module) { $blocks = filter ( satisfiesAll(['ignore' => not(), 'internal' => not()]), $module->blocks ); $contents = map(_f('generate_docs_contents_item'), $blocks); $module->docs .= join('', $contents); return $module; } /** * Generates an item of the documentation's contents. * * @signature Block -> String * @param object $block * @return string */ function generate_docs_contents_item($block) { if ($block->type != 'function') return ''; $params = join(', ', map(pipe(values(), join(' ')), get('params', $block))); $return = get('return', $block); $prototype = "```php\n{$block->name}({$params}) : {$return}\n```\n\n"; $signature = ''; $blockSignature = join("\n", $block->signatures); if ($blockSignature) $signature = "```\n{$blockSignature}\n```\n\n"; return "# {$block->name}\n\n{$prototype}{$signature}{$block->description}\n\n"; } /** * Generates tests contents for a module. * * @signature Module -> Module * @param object $module * @return object */ function generate_tests($module) { $module->tests = ''; $module->testsFooter = ''; return apply(process_of([ 'generate_tests_header', 'generate_tests_contents', 'generate_tests_footer' ]), [$module]); } /** * Generates module's tests header. * * @signature Module -> Module * @param object $module * @return object */ function generate_tests_header($module) { $namespace = "Tarsana\UnitTests\Functional"; $additionalNamespace = replace("/", "\\", remove(6, dirname($module->testsPath))); if ($additionalNamespace) $namespace .= "\\" . $additionalNamespace; $name = remove(-4, last(split("/", $module->testsPath))); $module->tests .= "<?php namespace {$namespace};\n\nuse Tarsana\Functional as F;\n\nclass {$name} extends \Tarsana\UnitTests\Functional\UnitTest {\n"; return $module; } /** * Generates module's tests contents. * * @signature Module -> Module * @param object $module * @return object */ function generate_tests_contents($module) { $blocks = filter ( satisfiesAll(['ignore' => not()]), $module->blocks ); $contents = join("\n", map(function($block) use($module) { return generate_tests_contents_item($block, $module); }, $blocks)); if (trim($contents) != '') $module->tests .= $contents; else $module->tests = ''; return $module; } /** * Generates a test for a module. * * @signature Block -> Module -> String * @param object $block * @param object $module * @return string */ function generate_tests_contents_item($block, $module) { if ($block->type != 'function') return ''; $code = apply(pipe( _f('code_from_description'), chunks("\"\"''{}[]()", "\n"), map(function($part) use($module) { return add_assertions($part, $module); }), filter(pipe('trim', notEq(''))), chain(split("\n")), map(prepend("\t\t")), join("\n") ), [$block]); if ('' == trim($code)) return ''; return prepend("\tpublic function test_{$block->name}() {\n", append("\n\t}\n", $code) ); } /** * Extracts the code snippet from the description of a block. * * @signature Block -> String * @param object $block * @return string */ function code_from_description($block) { $description = get('description', $block); if (!contains('```php', $description)) return ''; $code = remove(7 + indexOf('```php', $description), $description); return remove(-4, trim($code)); } /** * Adds assertions to a part of the code. * * @signature String -> String * @param string $part * @return string */ function add_assertions($part, $module) { if (contains('; //=> ', $part)) { $pieces = split('; //=> ', $part); $part = "\$this->assertEquals({$pieces[1]}, {$pieces[0]});"; } elseif (contains('; // throws ', $part)) { $pieces = split('; // throws ', $part); $variables = match('/ \$[0-9a-zA-Z_]+/', $pieces[0]); $use = ''; if (length($variables)) { $variables = join(', ', map('trim', $variables)); $use = "use({$variables}) "; } return "\$this->assertErrorThrown(function() {$use}{\n\t$pieces[0]; \n},\n{$pieces[1]});"; } elseif (startsWith('class ', $part) || startsWith('function ', $part)) { $module->testsFooter .= $part . "\n\n"; $part = ''; } return $part; } /** * Generates module's tests footer. * * @signature Module -> Module * @param object $module * @return object */ function generate_tests_footer($module) { if ($module->tests) $module->tests .= "}\n\n{$module->testsFooter}"; return $module; } /** * Generates module's stream operations. * * @signature Module -> Module * @param array $module * @return array */ function generate_stream_operations($module) { $blocks = filter ( satisfiesAll(['ignore' => equals(false), 'stream' => equals(true)]), $module->blocks ); $operations = map(_f('stream_operation_declaration'), chain(_f('stream_operations_of_block'), $blocks)); $module->streamOperations = join("", $operations); return $module; } /** * Gets stream operations from a block. * * @signature Block -> [Operation] * @param object $block * @return string */ function stream_operations_of_block($block) { return map(function($signature) use($block) { return (object) [ 'name' => $block->name, 'signature' => normalize_signature($signature) ]; }, get('signatures', $block)); } /** * Converts a formal signature to a stream signature. * [a] becomes List * {k: v} becomes Array|Object * (a -> b) becomes Function * * becomes Any * * @signature String -> String * @param string $signature * @return string */ function normalize_signature($signature) { // This is not the best way to do it :P return join(' -> ', map(pipe( regReplace('/Maybe\([a-z][^\)]*\)/', 'Any'), regReplace('/Maybe\(([^\)]+)\)/', '$1|Null'), regReplace('/\([^\)]+\)/', 'Function'), regReplace('/\[[^\]]+\]/', 'List'), regReplace('/\{[^\}]+\}/', 'Object|Array'), regReplace('/^.$/', 'Any'), regReplace('/[\(\)\[\]\{\}]/', '') ), chunks('(){}', ' -> ', $signature))); } /** * Converts a stream operation to declaration array. * * @signature Operation -> String * @param object $operation * @return string */ function stream_operation_declaration($operation) { $name = rtrim($operation->name, '_'); return "\t['{$name}', '{$operation->signature}', F\\{$operation->name}()],\n"; } /** * Generates module's stream methods documentation. * * @signature Module -> Module * @param array $module * @return array */ function generate_stream_methods($module) { $blocks = filter ( satisfiesAll(['ignore' => equals(false), 'stream' => equals(true)]), $module->blocks ); $methods = map(stream_method_link($module->name), $blocks); $module->streamMethods = (length($methods) > 0) ? "\n\n## {$module->name}\n\n" . join("\n", $methods) : ''; return $module; } /** * Gets an element of the stream methods list. * * @signature String -> Block -> String * @param string $moduleName * @param object $block * @return string */ function stream_method_link() { static $curried = false; $curried = $curried ?: curry(function($moduleName, $block) { return "- [{$block->name}](https://github.com/tarsana/functional/blob/master/docs/{$moduleName}.md#{$block->name}) - {$block->summary}\n"; }); return _apply($curried, func_get_args()); } /** * process_of(['f1', 'f2']) == pipe(_f('f1'), _f('f2')); * * @signature [String] -> Function * @param array $fns * @return callable */ function process_of($fns) { return apply(_f('pipe'), map(_f('_f'), $fns)); } /** * Dump a variable and returns it. * * @signature a -> a * @param mixed $something * @return mixed */ function log() { $log = function($something) { echo toString($something); return $something; }; return apply(curry($log), func_get_args()); } // Convert Warnings to Exceptions set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) { if (0 === error_reporting()) return false; throw new \ErrorException($errstr, 0, $errno, $errfile, $errline); }); // Run the build build_main(get_modules());
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter05/8.php
Chapter05/8.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $path = realpath('.'); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $name => $file) { echo "$name\n"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter05/4.php
Chapter05/4.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $dsn = "mysql:host=127.0.0.1;port=3306;dbname=packt;charset=UTF8;"; $username = "root"; $password = ""; $dbh = new PDO($dsn, $username, $password); $result = $dbh->query("Select * from categories order by parentCategory asc, sortInd asc", PDO::FETCH_OBJ); $categories = []; foreach($result as $row) { $categories[$row->parentCategory][] = $row; } function showCategoryTree(Array $categories, int $n) { if(isset($categories[$n])) { foreach($categories[$n] as $category) { echo str_repeat("-", $n)."".$category->categoryName."\n"; showCategoryTree($categories, $category->id); } } return; } showCategoryTree($categories, 0);
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter05/6.php
Chapter05/6.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function showFiles(string $dirName, Array &$allFiles = []) { $files = scandir($dirName); foreach ($files as $key => $value) { $path = realpath($dirName . DIRECTORY_SEPARATOR . $value); if (!is_dir($path)) { $allFiles[] = $path; } else if ($value != "." && $value != "..") { showFiles($path, $allFiles); $allFiles[] = $path; } } return; } $files = []; showFiles(".", $files); foreach($files as $file) { echo $file."\n"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter05/9.php
Chapter05/9.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $teams = array( 'Popular Football Teams', array( 'La Lega', array('Real Madrid', 'FC Barcelona', 'Athletico Madrid', 'Real Betis', 'Osasuna') ), array( 'English Premier League', array('Manchester United', 'Liverpool', 'Manchester City', 'Arsenal', 'Chelsea') ) ); $tree = new RecursiveTreeIterator( new RecursiveArrayIterator($teams), null, null, RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($tree as $leaf) echo $leaf . PHP_EOL;
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter05/7.php
Chapter05/7.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function maxDepth() { static $i = 0; print ++$i . "\n"; return 1+maxDepth(); } maxDepth();
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter05/10.php
Chapter05/10.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function array_sum_recursive(Array $array) { $sum = 0; array_walk_recursive($array, function($v) use (&$sum) { $sum += $v; }); return $sum; } $arr = [1, 2, 3, 4, 5, [6, 7, [8, 9, 10, [11, 12, 13, [14, 15, 16]]]]]; echo array_sum_recursive($arr);
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter05/5.php
Chapter05/5.php
<head> <style> ul { list-style: none; clear: both; } li ul { margin: 0px 0px 0px 50px; } .pic { display: block; width: 50px; height: 50px; float: left; color: #000; background: #ADDFEE; padding: 15px 10px; text-align: center; margin-right: 20px; } .comment { float: left; clear: both; margin: 20px; width: 500px; } .datetime { clear: right; width: 400px; margin-bottom: 10px; float: left; } </style> </head> <body> <?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $dsn = "mysql:host=127.0.0.1;port=3306;dbname=packt;charset=UTF8;"; $username = "root"; $password = ""; $dbh = new PDO($dsn, $username, $password); $sql = "Select * from comments where postID = :postID order by parentID asc, datetime asc"; $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); $stmt->setFetchMode(PDO::FETCH_OBJ); $stmt->execute(array(':postID' => 1)); $result = $stmt->fetchAll(); $comments = []; foreach ($result as $row) { $comments[$row->parentID][] = $row; } function displayComment(Array $comments, int $n) { if (isset($comments[$n])) { $str = "<ul>"; foreach ($comments[$n] as $comment) { $str .= "<li><div class='comment'><span class='pic'>{$comment->username}</span>"; $str .= "<span class='datetime'>{$comment->datetime}</span>"; $str .= "<span class='commenttext'>" . $comment->comment . "</span></div>"; $str .= displayComment($comments, $comment->id); $str .= "</li>"; } $str .= "</ul>"; return $str; } return ""; } echo displayComment($comments, 0); ?> </body>
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter05/3.php
Chapter05/3.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function gcd(int $a, int $b): int { if ($b == 0) { return $a; } else { return gcd($b, $a % $b); } } echo gcd(259,111);
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter05/1.php
Chapter05/1.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function factorialx(int $n): int { if ($n == 1) return 1; return $n * factorial($n - 1); } function factorial(int $n): int { $result = 1; for ($i = $n; $i > 0; $i--) { $result *= $i; } return $result; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter05/2.php
Chapter05/2.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function fibonacci(int $n): int { if($n == 0) { return 1; } else if($n == 1) { return 1; } else { return fibonacci($n-1) + fibonacci($n-2); } } echo fibonacci(20);
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter12/3.php
Chapter12/3.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $a = new \Ds\Vector([1, 2, 3]); $b = $a->copy(); $b->push(4); print_r($a); print_r($b); $vector = new \Ds\Vector(["a", "b", "c"]); echo $vector->get(1)."\n"; $vector[1] = "d"; echo $vector->get(1)."\n"; $vector->push('f'); echo "Size of vector: ".$vector->count()."\n"; $set = new \Ds\Set(); $set->add(1); $set->add(1); $set->add("test"); $set->add(3); echo $set->get(1);
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter12/1.php
Chapter12/1.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $inputStr = 'Bingo'; $fruites = ['Apple', 'Orange', 'Grapes', 'Banana', 'Water melon', 'Mango']; $matchScore = -1; $matchedStr = ''; foreach ($fruites as $fruit) { $tmpScore = levenshtein($inputStr, $fruit); if ($tmpScore == 0 || ($matchScore < 0 || $matchScore > $tmpScore)) { $matchScore = $tmpScore; $matchedStr = $fruit; } } echo $matchScore == 0 ? 'Exact match found : ' . $matchedStr : 'Did you mean: ' . $matchedStr . '?\n'; $str1 = "Mango"; $str2 = "Tango"; echo "Match length: " . similar_text($str1, $str2) . "\n"; similar_text($str1, $str2, $percent); echo "Percentile match: " . $percent . "%"; $word1 = "Pray"; $word2 = "Prey"; echo $word1 . " = " . soundex($word1) . "\n"; echo $word2 . " = " . soundex($word2) . "\n"; $word3 = "There"; $word4 = "Their"; echo $word3 . " = " . soundex($word3) . "\n"; echo $word4 . " = " . soundex($word4) . "\n"; $word1 = "Pray"; $word2 = "Prey"; echo $word1 . " = " . metaphone($word1) . "\n"; echo $word2 . " = " . metaphone($word2) . "\n"; $word3 = "There"; $word4 = "Their"; echo $word3 . " = " . metaphone($word3) . "\n"; echo $word4 . " = " . metaphone($word4) . "\n"; $arr = ['file1', 'file2', 'file10', 'file11', 'file3', 'file15', 'file21']; sort($arr); echo "Regular Sorting: " . implode(",", $arr)."\n"; natsort($arr); echo "Natural Sorting: " . implode(",", $arr); $data = "hello"; foreach (hash_algos() as $v) { $r = hash($v, $data, false); printf("%-12s %3d %s\n", $v, strlen($r), $r); }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter12/2.php
Chapter12/2.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $countries = []; array_push($countries, 'Bangladesh', 'Bhutan'); $countries = ["Bangladesh", "Nepal", "Bhutan"]; $key = array_search("Bangladesh", $countries); if ($key !== FALSE) echo "Found in: " . $key; else echo "Not found"; $countries = ["bangladesh", "nepal", "bhutan"]; $newCountries = array_map(function($country) { return strtoupper($country); }, $countries); foreach ($newCountries as $country) echo $country . "\n"; $countries = ["bangladesh", "nepal", "bhutan"]; $newCountries = array_map('strtoupper', $countries); foreach ($newCountries as $country) echo $country . "\n"; $countries = ["bangladesh", "nepal", "bhutan"]; $top = array_shift($countries); echo $top; $baseNumber = "123456754"; $newNumber = base_convert($baseNumber, 8, 16); echo $newNumber;
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter03/4.php
Chapter03/4.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ $BookTitles = new SplDoublyLinkedList(); $BookTitles->push("Introduction to Algorithm"); $BookTitles->push("Introduction to PHP and Data structures"); $BookTitles->push("Programming Intelligence"); $BookTitles->push("Mediawiki Administrative tutorial guide"); $BookTitles->add(1,"Introduction to Calculus"); $BookTitles->add(3,"Introduction to Graph Theory"); for($BookTitles->rewind();$BookTitles->valid();$BookTitles->next()){ echo $BookTitles->current()."\n"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter03/3.php
Chapter03/3.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class ListNode { public $data = NULL; public $next = NULL; public $prev = NULL; public function __construct(string $data = NULL) { $this->data = $data; } } class DoublyLinkedList { private $_firstNode = NULL; private $_lastNode = NULL; private $_totalNode = 0; public function insertAtFirst(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; $this->_lastNode = $newNode; } else { $currentFirstNode = $this->_firstNode; $this->_firstNode = &$newNode; $newNode->next = $currentFirstNode; $currentFirstNode->prev = $newNode; } $this->_totalNode++; return TRUE; } public function insertAtLast(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; $this->_lastNode = $newNode; } else { $currentNode = $this->_lastNode; $currentNode->next = $newNode; $newNode->prev = $currentNode; $this->_lastNode = $newNode; } $this->_totalNode++; return TRUE; } public function insertBefore(string $data = NULL, string $query = NULL) { $newNode = new ListNode($data); if ($this->_firstNode) { $previous = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { $newNode->next = $currentNode; $currentNode->prev = $newNode; $previous->next = $newNode; $newNode->prev = $previous; $this->_totalNode++; break; } $previous = $currentNode; $currentNode = $currentNode->next; } } } public function insertAfter(string $data = NULL, string $query = NULL) { $newNode = new ListNode($data); if ($this->_firstNode) { $nextNode = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { if ($nextNode !== NULL) { $newNode->next = $nextNode; } if ($currentNode === $this->_lastNode) { $this->_lastNode = $newNode; } $currentNode->next = $newNode; $nextNode->prev = $newNode; $newNode->prev = $currentNode; $this->_totalNode++; break; } $currentNode = $currentNode->next; $nextNode = $currentNode->next; } } } public function deleteFirst() { if ($this->_firstNode !== NULL) { if ($this->_firstNode->next !== NULL) { $this->_firstNode = $this->_firstNode->next; $this->_firstNode->prev = NULL; } else { $this->_firstNode = NULL; } $this->_totalNode--; return TRUE; } return FALSE; } public function deleteLast() { if ($this->_lastNode !== NULL) { $currentNode = $this->_lastNode; if ($currentNode->prev === NULL) { $this->_firstNode = NULL; $this->_lastNode = NULL; } else { $previousNode = $currentNode->prev; $this->_lastNode = $previousNode; $previousNode->next = NULL; $this->_totalNode--; return TRUE; } } return FALSE; } public function delete(string $query = NULL) { if ($this->_firstNode) { $previous = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { if ($currentNode->next === NULL) { $previous->next = NULL; } else { $previous->next = $currentNode->next; $currentNode->next->prev = $previous; } $this->_totalNode--; break; } $previous = $currentNode; $currentNode = $currentNode->next; } } } public function displayForward() { echo "Total book titles: " . $this->_totalNode . "\n"; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { echo $currentNode->data . "\n"; $currentNode = $currentNode->next; } } public function displayBackward() { echo "Total book titles: " . $this->_totalNode . "\n"; $currentNode = $this->_lastNode; while ($currentNode !== NULL) { echo $currentNode->data . "\n"; $currentNode = $currentNode->prev; } } public function getSize() { return $this->_totalNode; } } $BookTitles = new DoublyLinkedList(); $BookTitles->insertAtLast("Introduction to Algorithm"); $BookTitles->insertAtLast("Introduction to PHP and Data structures"); $BookTitles->insertAtLast("Programming Intelligence"); $BookTitles->insertAtFirst("Mediawiki Administrative tutorial guide"); $BookTitles->insertAfter("Introduction to Calculus", "Programming Intelligence"); $BookTitles->displayForward(); $BookTitles->displayBackward(); $BookTitles->deleteFirst(); $BookTitles->deleteLast(); $BookTitles->delete("Introduction to PHP and Data structures"); $BookTitles->displayForward(); $BookTitles->displayBackward(); //echo "2nd Item is: ".$BookTitles->getNthNode(2)->data;
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter03/1.php
Chapter03/1.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class ListNode { public $data = NULL; public $next = NULL; public function __construct(string $data = NULL) { $this->data = $data; } } class LinkedList implements Iterator { private $_firstNode = NULL; private $_totalNode = 0; private $_currentNode = NULL; private $_currentPosition = 0; public function insert(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; } else { $currentNode = $this->_firstNode; while ($currentNode->next !== NULL) { $currentNode = $currentNode->next; } $currentNode->next = $newNode; } $this->_totalNode++; return TRUE; } public function insertAtFirst(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; } else { $currentFirstNode = $this->_firstNode; $this->_firstNode = &$newNode; $newNode->next = $currentFirstNode; } $this->_totalNode++; return TRUE; } public function search(string $data = NULL) { if ($this->_totalNode) { $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $data) { return $currentNode; } $currentNode = $currentNode->next; } } return FALSE; } public function insertBefore(string $data = NULL, string $query = NULL) { $newNode = new ListNode($data); if ($this->_firstNode) { $previous = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { $newNode->next = $currentNode; $previous->next = $newNode; $this->_totalNode++; break; } $previous = $currentNode; $currentNode = $currentNode->next; } } } public function insertAfter(string $data = NULL, string $query = NULL) { $newNode = new ListNode($data); if ($this->_firstNode) { $nextNode = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { if ($nextNode !== NULL) { $newNode->next = $nextNode; } $currentNode->next = $newNode; $this->_totalNode++; break; } $currentNode = $currentNode->next; $nextNode = $currentNode->next; } } } public function deleteFirst() { if ($this->_firstNode !== NULL) { if ($this->_firstNode->next !== NULL) { $this->_firstNode = $this->_firstNode->next; } else { $this->_firstNode = NULL; } $this->_totalNode--; return TRUE; } return FALSE; } public function deleteLast() { if ($this->_firstNode !== NULL) { $currentNode = $this->_firstNode; if ($currentNode->next === NULL) { $this->_firstNode = NULL; } else { $previousNode = NULL; while ($currentNode->next !== NULL) { $previousNode = $currentNode; $currentNode = $currentNode->next; } $previousNode->next = NULL; $this->_totalNode--; return TRUE; } } return FALSE; } public function delete(string $query = NULL) { if ($this->_firstNode) { $previous = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($currentNode->data === $query) { if ($currentNode->next === NULL) { $previous->next = NULL; } else { $previous->next = $currentNode->next; } $this->_totalNode--; break; } $previous = $currentNode; $currentNode = $currentNode->next; } } } public function reverse() { if ($this->_firstNode !== NULL) { if ($this->_firstNode->next !== NULL) { $reversedList = NULL; $next = NULL; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { $next = $currentNode->next; $currentNode->next = $reversedList; $reversedList = $currentNode; $currentNode = $next; } $this->_firstNode = $reversedList; } } } public function getNthNode(int $n = 0) { $count = 1; if ($this->_firstNode !== NULL && $n <= $this->_totalNode) { $currentNode = $this->_firstNode; while ($currentNode !== NULL) { if ($count === $n) { return $currentNode; } $count++; $currentNode = $currentNode->next; } } } public function display() { echo "Total book titles: " . $this->_totalNode . "\n"; $currentNode = $this->_firstNode; while ($currentNode !== NULL) { echo $currentNode->data . "\n"; $currentNode = $currentNode->next; } } public function getSize() { return $this->_totalNode; } public function current() { return $this->_currentNode->data; } public function next() { $this->_currentPosition++; $this->_currentNode = $this->_currentNode->next; } public function key() { return $this->_currentPosition; } public function rewind() { $this->_currentPosition = 0; $this->_currentNode = $this->_firstNode; } public function valid() { return $this->_currentNode !== NULL; } } $BookTitles = new LinkedList(); $BookTitles->insert("Introduction to Algorithm"); $BookTitles->insert("Introduction to PHP and Data structures"); $BookTitles->insert("Programming Intelligence"); $BookTitles->insertAtFirst("Mediawiki Administrative tutorial guide"); $BookTitles->insertBefore("Introduction to Calculus", "Programming Intelligence"); $BookTitles->insertAfter("Introduction to Calculus", "Programming Intelligence"); foreach ($BookTitles as $title) { echo $title . "\n"; } for ($BookTitles->rewind(); $BookTitles->valid(); $BookTitles->next()) { echo $BookTitles->current() . "\n"; } /* $BookTitles->display(); $BookTitles->deleteFirst(); $BookTitles->deleteLast(); $BookTitles->delete("Introduction to PHP and Data structures"); $BookTitles->reverse(); $BookTitles->display(); echo "2nd Item is: ".$BookTitles->getNthNode(2)->data; * */
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter03/2.php
Chapter03/2.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ class ListNode { public $data = NULL; public $next = NULL; public function __construct(string $data = NULL) { $this->data = $data; } } class CircularLinkedList { private $_firstNode = NULL; private $_totalNode = 0; public function insertAtEnd(string $data = NULL) { $newNode = new ListNode($data); if ($this->_firstNode === NULL) { $this->_firstNode = &$newNode; } else { $currentNode = $this->_firstNode; while ($currentNode->next !== $this->_firstNode) { $currentNode = $currentNode->next; } $currentNode->next = $newNode; } $newNode->next = $this->_firstNode; $this->_totalNode++; return TRUE; } public function display() { echo "Total book titles: " . $this->_totalNode . "\n"; $currentNode = $this->_firstNode; while ($currentNode->next !== $this->_firstNode) { echo $currentNode->data . "\n"; $currentNode = $currentNode->next; } if ($currentNode) { echo $currentNode->data . "\n"; } } } $BookTitles = new CircularLinkedList(); $BookTitles->insertAtEnd("Introduction to Algorithm"); $BookTitles->insertAtEnd("Introduction to PHP and Data structures"); $BookTitles->insertAtEnd("Programming Intelligence"); $BookTitles->insertAtEnd("Mediawiki Administrative tutorial guide"); $BookTitles->display();
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter11/8.php
Chapter11/8.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ define("GC", "-"); define("SP", 1); define("GP", -1); define("MS", -1); function NWSquencing(string $s1, string $s2) { $grid = []; $M = strlen($s1); $N = strlen($s2); for ($i = 0; $i <= $N; $i++) { $grid[$i] = []; for ($j = 0; $j <= $M; $j++) { $grid[$i][$j] = null; } } $grid[0][0] = 0; for ($i = 1; $i <= $M; $i++) { $grid[0][$i] = -1 * $i; } for ($i = 1; $i <= $N; $i++) { $grid[$i][0] = -1 * $i; } for ($i = 1; $i <= $N; $i++) { for ($j = 1; $j <= $M; $j++) { $grid[$i][$j] = max( $grid[$i - 1][$j - 1] + ($s2[$i - 1] == $s1[$j - 1] ? SP : MS), $grid[$i - 1][$j] + GP, $grid[$i][$j - 1] + GP ); } } printSequence($grid, $s1, $s2, $M, $N); } function printSequence($grid, $s1, $s2, $j, $i) { $sq1 = []; $sq2 = []; $sq3 = []; do { $t = $grid[$i - 1][$j]; $d = $grid[$i - 1][$j - 1]; $l = $grid[$i][$j - 1]; $max = max($t, $d, $l); switch ($max) { case $d: $j--; $i--; array_push($sq1, $s1[$j]); array_push($sq2, $s2[$i]); if ($s1[$j] == $s2[$i]) array_push($sq3, "|"); else array_push($sq3, " "); break; case $t: $i--; array_push($sq1, GC); array_push($sq2, $s2[$i]); array_push($sq3, " "); break; case $l: $j--; array_push($sq1, $s1[$j]); array_push($sq2, GC); array_push($sq3, " "); break; } } while ($i > 0 && $j > 0); echo implode("", array_reverse($sq1)) . "\n"; echo implode("", array_reverse($sq3)) . "\n"; echo implode("", array_reverse($sq2)) . "\n"; } $X = "GAATTCAGTTA"; $Y = "GGATCGA"; NWSquencing($X, $Y);
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter11/4.php
Chapter11/4.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function huffmanEncode(array $symbols): array { $heap = new SplPriorityQueue; $heap->setExtractFlags(SplPriorityQueue::EXTR_BOTH); foreach ($symbols as $symbol => $weight) { $heap->insert(array($symbol => ''), -$weight); } while ($heap->count() > 1) { $low = $heap->extract(); $high = $heap->extract(); foreach ($low['data'] as &$x) $x = '0' . $x; foreach ($high['data'] as &$x) $x = '1' . $x; $heap->insert($low['data'] + $high['data'], $low['priority'] + $high['priority']); } $result = $heap->extract(); return $result['data']; } $txt = 'PHP 7 Data structures and Algorithms'; $symbols = array_count_values(str_split($txt)); $codes = huffmanEncode($symbols); echo "Symbol\t\tWeight\t\tHuffman Code\n"; foreach ($codes as $sym => $code) { echo "$sym\t\t$symbols[$sym]\t\t$code\n"; }
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false
PacktPublishing/PHP7-Data-Structures-and-Algorithms
https://github.com/PacktPublishing/PHP7-Data-Structures-and-Algorithms/blob/d5f228ce95b3c09fb173cd3243893ff658384d67/Chapter11/6.php
Chapter11/6.php
<?php /* * Example code for: PHP 7 Data Structures and Algorithms * * Author: Mizanur rahman <mizanur.rahman@gmail.com> * */ function knapSack(int $maxWeight, array $weights, array $values, int $n) { $DP = []; for ($i = 0; $i <= $n; $i++) { for ($w = 0; $w <= $maxWeight; $w++) { if ($i == 0 || $w == 0) $DP[$i][$w] = 0; else if ($weights[$i - 1] <= $w) $DP[$i][$w] = max($values[$i - 1] + $DP[$i - 1][$w - $weights[$i - 1]], $DP[$i - 1][$w]); else $DP[$i][$w] = $DP[$i - 1][$w]; } } return $DP[$n][$maxWeight]; } $values = [60, 100, 120, 280, 90]; $weights = [10, 20, 30, 40, 50]; $values = [10, 20, 30, 40, 50]; $weights = [1, 2, 3, 4, 5]; $maxWeight = 10; $n = count($values); echo knapSack($maxWeight, $weights, $values, $n);
php
MIT
d5f228ce95b3c09fb173cd3243893ff658384d67
2026-01-05T04:42:44.302062Z
false