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 |
|---|---|---|---|---|---|---|---|---|
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Exception/Formatter.php | src/Whoops/Exception/Formatter.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Exception;
use Whoops\Inspector\InspectorInterface;
class Formatter
{
/**
* Returns all basic information about the exception in a simple array
* for further convertion to other languages
* @param InspectorInterface $inspector
* @param bool $shouldAddTrace
* @param array<callable> $frameFilters
* @return array
*/
public static function formatExceptionAsDataArray(InspectorInterface $inspector, $shouldAddTrace, array $frameFilters = [])
{
$exception = $inspector->getException();
$response = [
'type' => get_class($exception),
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
];
if ($shouldAddTrace) {
$frames = $inspector->getFrames($frameFilters);
$frameData = [];
foreach ($frames as $frame) {
/** @var Frame $frame */
$frameData[] = [
'file' => $frame->getFile(),
'line' => $frame->getLine(),
'function' => $frame->getFunction(),
'class' => $frame->getClass(),
'args' => $frame->getArgs(),
];
}
$response['trace'] = $frameData;
}
return $response;
}
public static function formatExceptionPlain(InspectorInterface $inspector)
{
$message = $inspector->getException()->getMessage();
$frames = $inspector->getFrames();
$plain = $inspector->getExceptionName();
$plain .= ' thrown with message "';
$plain .= $message;
$plain .= '"'."\n\n";
$plain .= "Stacktrace:\n";
foreach ($frames as $i => $frame) {
$plain .= "#". (count($frames) - $i - 1). " ";
$plain .= $frame->getClass() ?: '';
$plain .= $frame->getClass() && $frame->getFunction() ? ":" : "";
$plain .= $frame->getFunction() ?: '';
$plain .= ' in ';
$plain .= ($frame->getFile() ?: '<#unknown>');
$plain .= ':';
$plain .= (int) $frame->getLine(). "\n";
}
return $plain;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Exception/Inspector.php | src/Whoops/Exception/Inspector.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Exception;
use Whoops\Inspector\InspectorFactory;
use Whoops\Inspector\InspectorInterface;
use Whoops\Util\Misc;
class Inspector implements InspectorInterface
{
/**
* @var \Throwable
*/
private $exception;
/**
* @var \Whoops\Exception\FrameCollection
*/
private $frames;
/**
* @var \Whoops\Exception\Inspector
*/
private $previousExceptionInspector;
/**
* @var \Throwable[]
*/
private $previousExceptions;
/**
* @var \Whoops\Inspector\InspectorFactoryInterface|null
*/
protected $inspectorFactory;
/**
* @param \Throwable $exception The exception to inspect
* @param \Whoops\Inspector\InspectorFactoryInterface $factory
*/
public function __construct($exception, $factory = null)
{
$this->exception = $exception;
$this->inspectorFactory = $factory ?: new InspectorFactory();
}
/**
* @return \Throwable
*/
public function getException()
{
return $this->exception;
}
/**
* @return string
*/
public function getExceptionName()
{
return get_class($this->exception);
}
/**
* @return string
*/
public function getExceptionMessage()
{
return $this->extractDocrefUrl($this->exception->getMessage())['message'];
}
/**
* @return string[]
*/
public function getPreviousExceptionMessages()
{
return array_map(function ($prev) {
/** @var \Throwable $prev */
return $this->extractDocrefUrl($prev->getMessage())['message'];
}, $this->getPreviousExceptions());
}
/**
* @return int[]
*/
public function getPreviousExceptionCodes()
{
return array_map(function ($prev) {
/** @var \Throwable $prev */
return $prev->getCode();
}, $this->getPreviousExceptions());
}
/**
* Returns a url to the php-manual related to the underlying error - when available.
*
* @return string|null
*/
public function getExceptionDocrefUrl()
{
return $this->extractDocrefUrl($this->exception->getMessage())['url'];
}
private function extractDocrefUrl($message)
{
$docref = [
'message' => $message,
'url' => null,
];
// php embbeds urls to the manual into the Exception message with the following ini-settings defined
// http://php.net/manual/en/errorfunc.configuration.php#ini.docref-root
if (!ini_get('html_errors') || !ini_get('docref_root')) {
return $docref;
}
$pattern = "/\[<a href='([^']+)'>(?:[^<]+)<\/a>\]/";
if (preg_match($pattern, $message, $matches)) {
// -> strip those automatically generated links from the exception message
$docref['message'] = preg_replace($pattern, '', $message, 1);
$docref['url'] = $matches[1];
}
return $docref;
}
/**
* Does the wrapped Exception has a previous Exception?
* @return bool
*/
public function hasPreviousException()
{
return $this->previousExceptionInspector || $this->exception->getPrevious();
}
/**
* Returns an Inspector for a previous Exception, if any.
* @todo Clean this up a bit, cache stuff a bit better.
* @return Inspector
*/
public function getPreviousExceptionInspector()
{
if ($this->previousExceptionInspector === null) {
$previousException = $this->exception->getPrevious();
if ($previousException) {
$this->previousExceptionInspector = $this->inspectorFactory->create($previousException);
}
}
return $this->previousExceptionInspector;
}
/**
* Returns an array of all previous exceptions for this inspector's exception
* @return \Throwable[]
*/
public function getPreviousExceptions()
{
if ($this->previousExceptions === null) {
$this->previousExceptions = [];
$prev = $this->exception->getPrevious();
while ($prev !== null) {
$this->previousExceptions[] = $prev;
$prev = $prev->getPrevious();
}
}
return $this->previousExceptions;
}
/**
* Returns an iterator for the inspected exception's
* frames.
*
* @param array<callable> $frameFilters
*
* @return \Whoops\Exception\FrameCollection
*/
public function getFrames(array $frameFilters = [])
{
if ($this->frames === null) {
$frames = $this->getTrace($this->exception);
// Fill empty line/file info for call_user_func_array usages (PHP Bug #44428)
foreach ($frames as $k => $frame) {
if (empty($frame['file'])) {
// Default values when file and line are missing
$file = '[internal]';
$line = 0;
$next_frame = !empty($frames[$k + 1]) ? $frames[$k + 1] : [];
if ($this->isValidNextFrame($next_frame)) {
$file = $next_frame['file'];
$line = $next_frame['line'];
}
$frames[$k]['file'] = $file;
$frames[$k]['line'] = $line;
}
}
// Find latest non-error handling frame index ($i) used to remove error handling frames
$i = 0;
foreach ($frames as $k => $frame) {
if ($frame['file'] == $this->exception->getFile() && $frame['line'] == $this->exception->getLine()) {
$i = $k;
}
}
// Remove error handling frames
if ($i > 0) {
array_splice($frames, 0, $i);
}
$firstFrame = $this->getFrameFromException($this->exception);
array_unshift($frames, $firstFrame);
$this->frames = new FrameCollection($frames);
if ($previousInspector = $this->getPreviousExceptionInspector()) {
// Keep outer frame on top of the inner one
$outerFrames = $this->frames;
$newFrames = clone $previousInspector->getFrames();
// I assume it will always be set, but let's be safe
if (isset($newFrames[0])) {
$newFrames[0]->addComment(
$previousInspector->getExceptionMessage(),
'Exception message:'
);
}
$newFrames->prependFrames($outerFrames->topDiff($newFrames));
$this->frames = $newFrames;
}
// Apply frame filters callbacks on the frames stack
if (!empty($frameFilters)) {
foreach ($frameFilters as $filterCallback) {
$this->frames->filter($filterCallback);
}
}
}
return $this->frames;
}
/**
* Gets the backtrace from an exception.
*
* If xdebug is installed
*
* @param \Throwable $e
* @return array
*/
protected function getTrace($e)
{
$traces = $e->getTrace();
// Get trace from xdebug if enabled, failure exceptions only trace to the shutdown handler by default
if (!$e instanceof \ErrorException) {
return $traces;
}
if (!Misc::isLevelFatal($e->getSeverity())) {
return $traces;
}
if (!extension_loaded('xdebug') || !function_exists('xdebug_is_enabled') || !xdebug_is_enabled()) {
return $traces;
}
// Use xdebug to get the full stack trace and remove the shutdown handler stack trace
$stack = array_reverse(xdebug_get_function_stack());
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$traces = array_diff_key($stack, $trace);
return $traces;
}
/**
* Given an exception, generates an array in the format
* generated by Exception::getTrace()
* @param \Throwable $exception
* @return array
*/
protected function getFrameFromException($exception)
{
return [
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'class' => get_class($exception),
'args' => [
$exception->getMessage(),
],
];
}
/**
* Given an error, generates an array in the format
* generated by ErrorException
* @param ErrorException $exception
* @return array
*/
protected function getFrameFromError(ErrorException $exception)
{
return [
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'class' => null,
'args' => [],
];
}
/**
* Determine if the frame can be used to fill in previous frame's missing info
* happens for call_user_func and call_user_func_array usages (PHP Bug #44428)
*
* @return bool
*/
protected function isValidNextFrame(array $frame)
{
if (empty($frame['file'])) {
return false;
}
if (empty($frame['line'])) {
return false;
}
if (empty($frame['function']) || !stristr($frame['function'], 'call_user_func')) {
return false;
}
return true;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Exception/ErrorException.php | src/Whoops/Exception/ErrorException.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Exception;
use ErrorException as BaseErrorException;
/**
* Wraps ErrorException; mostly used for typing (at least now)
* to easily cleanup the stack trace of redundant info.
*/
class ErrorException extends BaseErrorException
{
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/frame_code.html.php | src/Whoops/Resources/views/frame_code.html.php | <?php /* Display a code block for all frames in the stack.
* @todo: This should PROBABLY be done on-demand, lest
* we get 200 frames to process. */ ?>
<div class="frame-code-container <?php echo (!$has_frames ? 'empty' : '') ?>">
<?php foreach ($frames as $i => $frame): ?>
<?php $line = $frame->getLine(); ?>
<div class="frame-code <?php echo ($i == 0 ) ? 'active' : '' ?>" id="frame-code-<?php echo $i ?>">
<div class="frame-file">
<?php $filePath = $frame->getFile(); ?>
<?php if ($filePath && $editorHref = $handler->getEditorHref($filePath, (int) $line)): ?>
<a href="<?php echo $editorHref ?>" class="editor-link"<?php echo ($handler->getEditorAjax($filePath, (int) $line) ? ' data-ajax' : '') ?>>
Open:
<strong><?php echo $tpl->breakOnDelimiter('/', $tpl->escape($filePath ?: '<#unknown>')) ?></strong>
</a>
<?php else: ?>
<strong><?php echo $tpl->breakOnDelimiter('/', $tpl->escape($filePath ?: '<#unknown>')) ?></strong>
<?php endif ?>
</div>
<?php
// Do nothing if there's no line to work off
if ($line !== null):
// the $line is 1-indexed, we nab -1 where needed to account for this
$range = $frame->getFileLines($line - 20, 40);
// getFileLines can return null if there is no source code
if ($range):
$range = array_map(function ($line) { return empty($line) ? ' ' : $line;}, $range);
$start = key($range) + 1;
$code = join("\n", $range);
?>
<pre class="code-block line-numbers"
data-line="<?php echo $line ?>"
data-line-offset="<?php echo $start ?>"
data-start="<?php echo $start ?>"
><code class="language-php"><?php echo $tpl->escape($code) ?></code></pre>
<?php endif ?>
<?php endif ?>
<?php $frameArgs = $tpl->dumpArgs($frame); ?>
<?php if ($frameArgs): ?>
<div class="frame-file">
Arguments
</div>
<div id="frame-code-args-<?=$i?>" class="code-block frame-args">
<?php echo $frameArgs; ?>
</div>
<?php endif ?>
<?php
// Append comments for this frame
$comments = $frame->getComments();
?>
<div class="frame-comments <?php echo empty($comments) ? 'empty' : '' ?>">
<?php foreach ($comments as $commentNo => $comment): ?>
<?php extract($comment) ?>
<div class="frame-comment" id="comment-<?php echo $i . '-' . $commentNo ?>">
<span class="frame-comment-context"><?php echo $tpl->escape($context) ?></span>
<?php echo $tpl->escapeButPreserveUris($comment) ?>
</div>
<?php endforeach ?>
</div>
</div>
<?php endforeach ?>
</div>
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/header.html.php | src/Whoops/Resources/views/header.html.php | <div class="exception">
<div class="exc-title">
<?php foreach ($name as $i => $nameSection): ?>
<?php if ($i == count($name) - 1): ?>
<span class="exc-title-primary"><?php echo $tpl->escape($nameSection) ?></span>
<?php else: ?>
<?php echo $tpl->escape($nameSection) . ' \\' ?>
<?php endif ?>
<?php endforeach ?>
<?php if ($code): ?>
<span title="Exception Code">(<?php echo $tpl->escape($code) ?>)</span>
<?php endif ?>
</div>
<div class="exc-message">
<?php if (!empty($message)): ?>
<span><?php echo $tpl->escape($message) ?></span>
<?php if (count($previousMessages)): ?>
<div class="exc-title prev-exc-title">
<span class="exc-title-secondary">Previous exceptions</span>
</div>
<ul>
<?php foreach ($previousMessages as $i => $previousMessage): ?>
<li>
<?php echo $tpl->escape($previousMessage) ?>
<span class="prev-exc-code">(<?php echo $previousCodes[$i] ?>)</span>
</li>
<?php endforeach; ?>
</ul>
<?php endif ?>
<?php else: ?>
<span class="exc-message-empty-notice">No message</span>
<?php endif ?>
<ul class="search-for-help">
<?php if (!empty($docref_url)): ?>
<li>
<a rel="noopener noreferrer" target="_blank" href="<?php echo $docref_url; ?>" title="Search for help in the PHP manual.">
<!-- PHP icon by Icons Solid -->
<!-- https://www.iconfinder.com/icons/322421/book_icon -->
<!-- Free for commercial use -->
<svg height="16px" id="Layer_1" style="enable-background:new 0 0 32 32;" version="1.1" viewBox="0 0 32 32" width="16px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g transform="translate(240 0)"><path d="M-211,4v26h-24c-1.104,0-2-0.895-2-2s0.896-2,2-2h22V0h-22c-2.209,0-4,1.791-4,4v24c0,2.209,1.791,4,4,4h26V4H-211z M-235,8V2h20v22h-20V8z M-219,6h-12V4h12V6z M-223,10h-8V8h8V10z M-227,14h-4v-2h4V14z"/></g></svg>
</a>
</li>
<?php endif ?>
<li>
<a rel="noopener noreferrer" target="_blank" href="https://google.com/search?q=<?php echo urlencode(implode('\\', $name).' '.$message) ?>" title="Search for help on Google.">
<!-- Google icon by Alfredo H, from https://www.iconfinder.com/alfredoh -->
<!-- Creative Commons (Attribution 3.0 Unported) -->
<!-- http://creativecommons.org/licenses/by/3.0/ -->
<svg class="google" height="16" viewBox="0 0 512 512" width="16" xmlns="http://www.w3.org/2000/svg">
<path d="M457.732 216.625c2.628 14.04 4.063 28.743 4.063 44.098C461.795 380.688 381.48 466 260.205 466c-116.024 0-210-93.977-210-210s93.976-210 210-210c56.703 0 104.076 20.867 140.44 54.73l-59.205 59.197v-.135c-22.046-21.002-50-31.762-81.236-31.762-69.297 0-125.604 58.537-125.604 127.84 0 69.29 56.306 127.97 125.604 127.97 62.87 0 105.653-35.966 114.46-85.313h-114.46v-81.902h197.528z"/>
</svg>
</a>
</li>
<li>
<a rel="noopener noreferrer" target="_blank" href="https://duckduckgo.com/?q=<?php echo urlencode(implode('\\', $name).' '.$message) ?>" title="Search for help on DuckDuckGo.">
<!-- DuckDuckGo icon by IconBaandar Team, from https://www.iconfinder.com/iconbaandar -->
<!-- Creative Commons (Attribution 3.0 Unported) -->
<!-- http://creativecommons.org/licenses/by/3.0/ -->
<svg class="duckduckgo" height="16" viewBox="150 150 1675 1675" width="16" xmlns="http://www.w3.org/2000/svg">
<path d="M1792 1024c0 204.364-80.472 398.56-224.955 543.04-144.483 144.48-338.68 224.95-543.044 224.95-204.36 0-398.56-80.47-543.04-224.95-144.48-144.482-224.95-338.676-224.95-543.04 0-204.365 80.47-398.562 224.96-543.045C625.44 336.47 819.64 256 1024 256c204.367 0 398.565 80.47 543.05 224.954C1711.532 625.437 1792 819.634 1792 1024zm-270.206 497.787C1654.256 1389.327 1728 1211.36 1728 1024c0-187.363-73.74-365.332-206.203-497.796C1389.332 393.74 1211.363 320 1024 320s-365.33 73.742-497.795 206.205C393.742 658.67 320 836.637 320 1024c0 187.36 73.744 365.326 206.206 497.787C658.67 1654.25 836.638 1727.99 1024 1727.99c187.362 0 365.33-73.74 497.794-206.203z"/>
<path d="M1438.64 1177.41c0-.03-.005-.017-.01.004l.01-.004z"/>
<path d="M1499.8 976.878c.03-.156-.024-.048-.11.107l.11-.107z"/>
<path d="M1105.19 991.642zm-68.013-376.128c-8.087-10.14-18.028-19.965-29.89-29.408-13.29-10.582-29-20.76-47.223-30.443-35.07-18.624-74.482-31.61-115.265-38.046-39.78-6.28-80.84-6.256-120.39.917l1.37 31.562c1.8.164 7.7 3.9 14.36 8.32-20.68 5.94-39.77 14.447-39.48 39.683l.2 17.48 17.3-1.73c29.38-2.95 60.17-2.06 90.32 2.61 9.21 1.42 18.36 3.2 27.38 5.32l-4.33 1.15c-20.45 5.58-38.93 12.52-54.25 20.61-46.28 24.32-75.51 60.85-90.14 108.37-14.14 45.95-14.27 101.81-2.72 166.51l.06.06c15.14 84.57 64.16 316.39 104.11 505.39 19.78 93.59 37.38 176.83 47.14 224.4 3.26 15.84 5.03 31.02 5.52 45.52.3 9.08.09 17.96-.58 26.62-.45 5.8-1.11 11.51-1.96 17.112l31.62 4.75c.71-4.705 1.3-9.494 1.76-14.373 48.964 10.517 99.78 16.05 151.88 16.05 60.68 0 119.61-7.505 175.91-21.64 3.04 6.08 6.08 12.19 9.11 18.32l28.62-14.128c-2.11-4.27-4.235-8.55-6.37-12.84-23.005-46.124-47.498-93.01-68.67-133.534-15.39-29.466-29.01-55.53-39.046-75.58-26.826-53.618-53.637-119.47-68.28-182.368-8.78-37.705-13.128-74.098-10.308-105.627-15.31-6.28-26.69-11.8-31.968-15.59l-.01.015c-14.22-10.2-31.11-28.12-41.82-49.717-8.618-17.376-13.4-37.246-10.147-57.84 3.17-19.84 27.334-46.714 57.843-67.46v-.063c26.554-18.05 58.75-32.506 86.32-34.31 7.835-.51 16.31-1.008 23.99-1.45 33.45-1.95 50.243-2.93 84.475-11.42 10.88-2.697 26.19-6.56 43.53-11.09 2.364-40.7-5.947-87.596-21.04-133.234-22.004-66.53-58.68-131.25-97.627-170.21-12.543-12.55-28.17-22.79-45.9-30.933-16.88-7.753-35.64-13.615-55.436-17.782zm-10.658 178.553s6.77-42.485 58.39-33.977c27.96 4.654 37.89 29.833 37.89 29.833s-25.31-14.46-44.95-14.198c-40.33.53-51.35 18.342-51.35 18.342zm-240.45-18.802c48.49-19.853 72.11 11.298 72.11 11.298s-35.21-15.928-69.46 5.59c-34.19 21.477-32.92 43.452-32.92 43.452s-18.17-40.5 30.26-60.34zm296.5 95.4c0-6.677 2.68-12.694 7.01-17.02 4.37-4.37 10.42-7.074 17.1-7.074 6.73 0 12.79 2.7 17.15 7.05 4.33 4.33 7.01 10.36 7.01 17.05 0 6.74-2.7 12.81-7.07 17.18-4.33 4.33-10.37 7.01-17.1 7.01-6.68 0-12.72-2.69-17.05-7.03-4.36-4.37-7.07-10.43-7.07-17.16zm-268.42 51.27c0-8.535 3.41-16.22 8.93-21.738 5.55-5.55 13.25-8.982 21.81-8.982 8.51 0 16.18 3.415 21.7 8.934 5.55 5.55 8.98 13.25 8.98 21.78 0 8.53-3.44 16.23-8.98 21.79-5.52 5.52-13.19 8.93-21.71 8.93-8.55 0-16.26-3.43-21.82-8.99-5.52-5.52-8.93-13.2-8.93-21.74z"/>
<path d="M1102.48 986.34zm390.074-64.347c-28.917-11.34-74.89-12.68-93.32-3.778-11.5 5.567-35.743 13.483-63.565 21.707-25.75 7.606-53.9 15.296-78.15 21.702-17.69 4.67-33.3 8.66-44.4 11.435-34.92 8.76-52.05 9.77-86.17 11.78-7.84.46-16.48.97-24.48 1.5-28.12 1.86-60.97 16.77-88.05 35.4v.06c-31.12 21.4-55.77 49.12-59.01 69.59-3.32 21.24 1.56 41.74 10.35 59.67 10.92 22.28 28.15 40.77 42.66 51.29l.01-.02c5.38 3.9 16.98 9.6 32.6 16.08 26.03 10.79 63.2 23.76 101.25 34.23 43.6 11.99 89.11 21.05 121.69 20.41 34.26-.69 77.73-10.52 114.54-24.67 22.15-8.52 42.21-18.71 56.88-29.58 17.85-13.22 28.7-28.42 28.4-44.74-.07-3.89-.72-7.63-1.97-11.21l-.02.01c-11.6-33.06-50.37-23.59-105.53-10.12-46.86 11.445-107.94 26.365-169.01 20.434-32.56-3.167-54.45-10.61-67.88-20.133-5.96-4.224-9.93-8.67-12.18-13.11-1.96-3.865-2.68-7.84-2.33-11.714.39-4.42 2.17-9.048 5.1-13.57l-.05-.03c7.86-12.118 23.082-9.72 43.93-6.43 25.91 4.08 58.2 9.172 99.013-3.61 39.63-12.378 87.76-29.9 131.184-47.39 42.405-17.08 80.08-34.078 100.74-46.18 25.46-14.87 37.57-29.428 40.59-42.866 2.725-12.152-.89-22.48-8.903-31.07-5.87-6.29-14.254-11.31-23.956-15.115z"/>
</svg>
</a>
</li>
<li>
<a rel="noopener noreferrer" target="_blank" href="https://stackoverflow.com/search?q=<?php echo urlencode(implode('\\', $name).' '.$message) ?>" title="Search for help on Stack Overflow.">
<!-- Stack Overflow icon by Picons.me, from https://www.iconfinder.com/Picons -->
<!-- Free for commercial use -->
<svg class="stackoverflow" height="16" viewBox="-1163 1657.697 56.693 56.693" width="16" xmlns="http://www.w3.org/2000/svg">
<path d="M-1126.04 1689.533l-16.577-9.778 2.088-3.54 16.578 9.778zM-1127.386 1694.635l-18.586-4.996 1.068-3.97 18.586 4.995zM-1127.824 1700.137l-19.165-1.767.378-4.093 19.165 1.767zM-1147.263 1701.293h19.247v4.11h-19.247z"/>
<path d="M-1121.458 1710.947s0 .96-.032.96v.016h-30.796s-.96 0-.96-.016h-.032v-20.03h3.288v16.805h25.244v-16.804h3.288v19.07zM-1130.667 1667.04l10.844 15.903-3.396 2.316-10.843-15.903zM-1118.313 1663.044l3.29 18.963-4.05.703-3.29-18.963z"/>
</svg>
</a>
</li>
</ul>
<span id="plain-exception"><?php echo $tpl->escape($plain_exception) ?></span>
<button id="copy-button" class="rightButton clipboard" data-clipboard-text="<?php echo $tpl->escape($plain_exception) ?>" title="Copy exception details to clipboard">
COPY
</button>
<button id="hide-error" class="rightButton" title="Hide error message" onclick="document.getElementsByClassName('Whoops')[0].style.display = 'none';">
HIDE
</button>
</div>
</div>
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/layout.html.php | src/Whoops/Resources/views/layout.html.php | <?php
/**
* Layout template file for Whoops's pretty error output.
*/
?>
<!DOCTYPE html><?php echo $preface; ?>
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex,nofollow"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<title><?php echo $tpl->escape($page_title) ?></title>
<style><?php echo $stylesheet ?></style>
<style><?php echo $prismCss ?></style>
</head>
<body>
<div class="Whoops container">
<div class="stack-container">
<?php $tpl->render($panel_left_outer) ?>
<?php $tpl->render($panel_details_outer) ?>
</div>
</div>
<script data-manual><?php echo $prismJs ?></script>
<script><?php echo $zepto ?></script>
<script><?php echo $clipboard ?></script>
<script><?php echo $javascript ?></script>
</body>
</html>
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/frames_container.html.php | src/Whoops/Resources/views/frames_container.html.php | <div class="frames-container <?php echo $active_frames_tab == 'application' ? 'frames-container-application' : '' ?>">
<?php $tpl->render($frame_list) ?>
</div> | php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/frames_description.html.php | src/Whoops/Resources/views/frames_description.html.php | <div class="frames-description <?php echo $has_frames_tabs ? 'frames-description-application' : '' ?>">
<?php if ($has_frames_tabs): ?>
<a href="#" id="application-frames-tab" class="frames-tab <?php echo $active_frames_tab == 'application' ? 'frames-tab-active' : '' ?>">
Application frames (<?php echo $frames->countIsApplication() ?>)
</a>
<a href="#" id="all-frames-tab" class="frames-tab <?php echo $active_frames_tab == 'all' ? 'frames-tab-active' : '' ?>">
All frames (<?php echo count($frames) ?>)
</a>
<?php else: ?>
<span>
Stack frames (<?php echo count($frames) ?>)
</span>
<?php endif; ?>
</div>
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/env_details.html.php | src/Whoops/Resources/views/env_details.html.php | <?php /* List data-table values, i.e: $_SERVER, $_GET, .... */ ?>
<div class="details">
<h2 class="details-heading">Environment & details:</h2>
<div class="data-table-container" id="data-tables">
<?php foreach ($tables as $label => $data): ?>
<div class="data-table" id="sg-<?php echo $tpl->escape($tpl->slug($label)) ?>">
<?php if (!empty($data)): ?>
<label><?php echo $tpl->escape($label) ?></label>
<table class="data-table">
<thead>
<tr>
<td class="data-table-k">Key</td>
<td class="data-table-v">Value</td>
</tr>
</thead>
<?php foreach ($data as $k => $value): ?>
<tr>
<td><?php echo $tpl->escape($k) ?></td>
<td><?php echo $tpl->dump($value) ?></td>
</tr>
<?php endforeach ?>
</table>
<?php else: ?>
<label class="empty"><?php echo $tpl->escape($label) ?></label>
<span class="empty">empty</span>
<?php endif ?>
</div>
<?php endforeach ?>
</div>
<?php /* List registered handlers, in order of first to last registered */ ?>
<div class="data-table-container" id="handlers">
<label>Registered Handlers</label>
<?php foreach ($handlers as $i => $h): ?>
<div class="handler <?php echo ($h === $handler) ? 'active' : ''?>">
<?php echo $i ?>. <?php echo $tpl->escape(get_class($h)) ?>
</div>
<?php endforeach ?>
</div>
</div>
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/panel_details_outer.html.php | src/Whoops/Resources/views/panel_details_outer.html.php | <div class="panel details-container cf">
<?php $tpl->render($panel_details) ?>
</div> | php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/panel_details.html.php | src/Whoops/Resources/views/panel_details.html.php | <?php $tpl->render($frame_code) ?>
<?php $tpl->render($env_details) ?> | php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/header_outer.html.php | src/Whoops/Resources/views/header_outer.html.php | <header>
<?php $tpl->render($header) ?>
</header>
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/frame_list.html.php | src/Whoops/Resources/views/frame_list.html.php | <?php /* List file names & line numbers for all stack frames;
clicking these links/buttons will display the code view
for that particular frame */ ?>
<?php foreach ($frames as $i => $frame): ?>
<div class="frame <?php echo ($i == 0 ? 'active' : '') ?> <?php echo ($frame->isApplication() ? 'frame-application' : '') ?>" id="frame-line-<?php echo $i ?>">
<span class="frame-index"><?php echo (count($frames) - $i - 1) ?></span>
<div class="frame-method-info">
<span class="frame-class"><?php echo $tpl->breakOnDelimiter('\\', $tpl->escape($frame->getClass() ?: '')) ?></span>
<span class="frame-function"><?php echo $tpl->breakOnDelimiter('\\', $tpl->escape($frame->getFunction() ?: '')) ?></span>
</div>
<div class="frame-file">
<?php echo $frame->getFile() ? $tpl->breakOnDelimiter('/', $tpl->shorten($tpl->escape($frame->getFile()))) : '<#unknown>' ?><!--
--><span class="frame-line">:<?php echo (int) $frame->getLine() ?></span>
</div>
</div>
<?php endforeach;
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/panel_left_outer.html.php | src/Whoops/Resources/views/panel_left_outer.html.php | <div class="panel left-panel cf <?php echo (!$has_frames ? 'empty' : '') ?>">
<?php $tpl->render($panel_left) ?>
</div> | php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/src/Whoops/Resources/views/panel_left.html.php | src/Whoops/Resources/views/panel_left.html.php | <?php
$tpl->render($header_outer);
$tpl->render($frames_description);
$tpl->render($frames_container);
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/bootstrap.php | tests/bootstrap.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*
* Bootstrapper for PHPUnit tests.
*/
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/fixtures/template.php | tests/fixtures/template.php | <?php echo $tpl->slug("hello world!"); ?>
My name is <?php echo $tpl->escape($name) ?>
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/fixtures/frame.lines-test.php | tests/fixtures/frame.lines-test.php | <?php
// Line 2
// Line 3
// Line 4
// Line 5
// Line 6
// Line 7
// Line 8
// Line 9
// Line 10
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/TestCase.php | tests/Whoops/TestCase.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops;
use PHPUnit\Framework\TestCase as BaseTestCase;
class TestCase extends BaseTestCase
{
/**
* @return Run
*/
protected function getRunInstance()
{
$run = new Run();
$run->allowQuit(false);
return $run;
}
/**
* @param string $class
* @return void
*/
protected function expectExceptionOfType($class)
{
if (method_exists($this, 'expectException')) {
$this->expectException($class);
} else {
$this->setExpectedException($class);
}
}
/**
* @param string $a
* @param string $b
* @return void
*/
protected function assertStringContains($a, $b)
{
if (method_exists($this, 'assertStringContainsString')) {
$this->assertStringContainsString($a, $b);
} else {
$this->assertContains($a, $b);
}
}
/**
* @param string $a
* @param string $b
* @return void
*/
protected function assertStringNotContains($a, $b)
{
if (method_exists($this, 'assertStringNotContainsString')) {
$this->assertStringNotContainsString($a, $b);
} else {
$this->assertNotContains($a, $b);
}
}
/**
* @param object|string $class_or_object
* @param string $method
* @param mixed[] $args
* @return mixed
*/
public static function callPrivateMethod($class_or_object, $method, $args = [])
{
$ref = new \ReflectionMethod($class_or_object, $method);
// setAccessible does not do anything starting with 8.1, throws starting with 8.5
if (PHP_VERSION_ID < 80100) {
$ref->setAccessible(true);
}
$object = is_object($class_or_object) ? $class_or_object : null;
return $ref->invokeArgs($object, $args);
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/RunTest.php | tests/Whoops/RunTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops;
use ArrayObject;
use Exception;
use InvalidArgumentException;
use Mockery as m;
use RuntimeException;
use Whoops\Handler\Handler;
use Whoops\Handler\HandlerInterface;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Exception\Frame;
use Whoops\Util\SystemFacade;
class RunTest extends TestCase
{
public function testImplementsRunInterface()
{
$this->assertNotFalse(class_implements('Whoops\\Run', 'Whoops\\RunInterface'));
}
public function testConstantsAreAccessibleFromTheClass()
{
$this->assertEquals(RunInterface::ERROR_HANDLER, Run::ERROR_HANDLER);
$this->assertEquals(RunInterface::EXCEPTION_HANDLER, Run::EXCEPTION_HANDLER);
$this->assertEquals(RunInterface::SHUTDOWN_HANDLER, Run::SHUTDOWN_HANDLER);
}
/**
* @param string $message
* @return Exception
*/
protected function getException($message = "")
{
// HHVM does not support mocking exceptions
// Since we do not use any additional features of Mockery for exceptions,
// we can just use native Exceptions instead.
return new \Exception($message);
}
/**
* @return Handler
*/
protected function getHandler()
{
return m::mock('Whoops\\Handler\\Handler')
->shouldReceive('setRun')
->andReturn(null)
->mock()
->shouldReceive('setInspector')
->andReturn(null)
->mock()
->shouldReceive('setException')
->andReturn(null)
->mock();
}
/**
* @covers Whoops\Run::clearHandlers
*/
public function testClearHandlers()
{
$run = $this->getRunInstance();
$run->clearHandlers();
$handlers = $run->getHandlers();
$this->assertEmpty($handlers);
}
/**
* @covers Whoops\Run::pushHandler
*/
public function testPushHandler()
{
$run = $this->getRunInstance();
$run->clearHandlers();
$handlerOne = $this->getHandler();
$handlerTwo = $this->getHandler();
$run->pushHandler($handlerOne);
$run->pushHandler($handlerTwo);
$handlers = $run->getHandlers();
$this->assertCount(2, $handlers);
$this->assertContains($handlerOne, $handlers);
$this->assertContains($handlerTwo, $handlers);
}
/**
* @covers Whoops\Run::pushHandler
*/
public function testPushInvalidHandler()
{
$run = $this->getRunInstance();
$this->expectExceptionOfType('InvalidArgumentException');
$run->pushHandler('actually turnip');
}
/**
* @covers Whoops\Run::pushHandler
*/
public function testPushClosureBecomesHandler()
{
$run = $this->getRunInstance();
$run->pushHandler(function () {});
$this->assertInstanceOf('Whoops\\Handler\\CallbackHandler', $run->popHandler());
}
/**
* @covers Whoops\Run::popHandler
* @covers Whoops\Run::getHandlers
*/
public function testPopHandler()
{
$run = $this->getRunInstance();
$handlerOne = $this->getHandler();
$handlerTwo = $this->getHandler();
$handlerThree = $this->getHandler();
$run->pushHandler($handlerOne);
$run->pushHandler($handlerTwo);
$run->pushHandler($handlerThree);
$this->assertSame($handlerThree, $run->popHandler());
$this->assertSame($handlerTwo, $run->popHandler());
$this->assertSame($handlerOne, $run->popHandler());
// Should return null if there's nothing else in
// the stack
$this->assertNull($run->popHandler());
// Should be empty since we popped everything off
// the stack:
$this->assertEmpty($run->getHandlers());
}
/**
* @covers Whoops\Run::removeFirstHandler
* @covers Whoops\Run::removeLastHandler
* @covers Whoops\Run::getHandlers
*/
public function testRemoveHandler()
{
$run = $this->getRunInstance();
$handlerOne = $this->getHandler();
$handlerTwo = $this->getHandler();
$handlerThree = $this->getHandler();
$run->pushHandler($handlerOne);
$run->pushHandler($handlerTwo);
$run->pushHandler($handlerThree);
$run->removeLastHandler();
$this->assertSame($handlerTwo, $run->getHandlers()[0]);
$run->removeFirstHandler();
$this->assertSame($handlerTwo, $run->getHandlers()[0]);
$this->assertCount(1, $run->getHandlers());
}
/**
* @covers Whoops\Run::register
*/
public function testRegisterHandler()
{
// It is impossible to test the Run::register method using phpunit,
// as given how every test is always inside a giant try/catch block,
// any thrown exception will never hit a global exception handler.
// On the other hand, there is not much need in testing
// a call to a native PHP function.
$this->assertTrue(true);
}
/**
* @covers Whoops\Run::unregister
*/
public function testUnregisterHandler()
{
$run = $this->getRunInstance();
$run->register();
$handler = $this->getHandler();
$run->pushHandler($handler);
$run->unregister();
$this->expectExceptionOfType('Exception');
throw $this->getException("I'm not supposed to be caught!");
}
/**
* @covers Whoops\Run::pushHandler
* @covers Whoops\Run::getHandlers
*/
public function testHandlerHoldsOrder()
{
$run = $this->getRunInstance();
$handlerOne = $this->getHandler();
$handlerTwo = $this->getHandler();
$handlerThree = $this->getHandler();
$handlerFour = $this->getHandler();
$run->pushHandler($handlerOne);
$run->prependHandler($handlerTwo);
$run->appendHandler($handlerThree);
$run->appendHandler($handlerFour);
$handlers = $run->getHandlers();
$this->assertSame($handlers[0], $handlerFour);
$this->assertSame($handlers[1], $handlerThree);
$this->assertSame($handlers[2], $handlerOne);
$this->assertSame($handlers[3], $handlerTwo);
}
/**
* @todo possibly split this up a bit and move
* some of this test to Handler unit tests?
* @covers Whoops\Run::handleException
*/
public function testHandlersGonnaHandle()
{
$run = $this->getRunInstance();
$exception = $this->getException();
$order = new ArrayObject();
$handlerOne = $this->getHandler();
$handlerTwo = $this->getHandler();
$handlerThree = $this->getHandler();
$handlerOne->shouldReceive('handle')
->andReturnUsing(function () use ($order) { $order[] = 1; });
$handlerTwo->shouldReceive('handle')
->andReturnUsing(function () use ($order) { $order[] = 2; });
$handlerThree->shouldReceive('handle')
->andReturnUsing(function () use ($order) { $order[] = 3; });
$run->pushHandler($handlerOne);
$run->pushHandler($handlerTwo);
$run->pushHandler($handlerThree);
// Get an exception to be handled, and verify that the handlers
// are given the handler, and in the inverse order they were
// registered.
$run->handleException($exception);
$this->assertEquals((array) $order, [3, 2, 1]);
}
/**
* @covers Whoops\Run::handleException
*/
public function testLastHandler()
{
$run = $this->getRunInstance();
$handlerOne = $this->getHandler();
$handlerTwo = $this->getHandler();
$handlerThree = $this->getHandler();
$handlerFour = $this->getHandler();
$run->pushHandler($handlerOne);
$run->prependHandler($handlerTwo);
$run->appendHandler($handlerThree);
$run->appendHandler($handlerFour);
$test = $this;
$handlerFour
->shouldReceive('handle')
->andReturnUsing(function () use ($test) {
$test->fail('$handlerFour should not be called');
});
$handlerThree
->shouldReceive('handle')
->andReturn(Handler::LAST_HANDLER);
$twoRan = false;
$handlerOne
->shouldReceive('handle')
->andReturnUsing(function () use ($test, &$twoRan) {
$test->assertTrue($twoRan);
});
$handlerTwo
->shouldReceive('handle')
->andReturnUsing(function () use (&$twoRan) {
$twoRan = true;
});
$run->handleException($this->getException());
// Reached the end without errors
$this->assertTrue(true);
}
/**
* Test error suppression using @ operator.
*/
public function testErrorSuppression()
{
$run = $this->getRunInstance();
$run->register();
$handler = $this->getHandler();
$run->pushHandler($handler);
$test = $this;
$handler
->shouldReceive('handle')
->andReturnUsing(function () use ($test) {
$test->fail('$handler should not be called, error not suppressed');
});
@trigger_error("Test error suppression");
// Reached the end without errors
$this->assertTrue(true);
}
public function testErrorCatching()
{
$run = $this->getRunInstance();
$run->register();
$handler = $this->getHandler();
$run->pushHandler($handler);
$test = $this;
$handler
->shouldReceive('handle')
->andReturnUsing(function () use ($test) {
$test->fail('$handler should not be called error should be caught');
});
try {
trigger_error('foo', E_USER_NOTICE);
$this->fail('Should not continue after error thrown');
} catch (\ErrorException $e) {
// Do nothing
$this->assertTrue(true);
return;
}
$this->fail('Should not continue here, should have been caught.');
}
/**
* Test to make sure that error_reporting is respected.
*/
public function testErrorReporting()
{
$run = $this->getRunInstance();
$run->register();
$handler = $this->getHandler();
$run->pushHandler($handler);
$test = $this;
$handler
->shouldReceive('handle')
->andReturnUsing(function () use ($test) {
$test->fail('$handler should not be called, error_reporting not respected');
});
$oldLevel = error_reporting(E_ALL ^ E_USER_NOTICE);
trigger_error("Test error reporting", E_USER_NOTICE);
error_reporting($oldLevel);
// Reached the end without errors
$this->assertTrue(true);
}
/**
* @covers Whoops\Run::silenceErrorsInPaths
*/
public function testSilenceErrorsInPaths()
{
$run = $this->getRunInstance();
$run->register();
$handler = $this->getHandler();
$run->pushHandler($handler);
$test = $this;
$handler
->shouldReceive('handle')
->andReturnUsing(function () use ($test) {
$test->fail('$handler should not be called, silenceErrorsInPaths not respected');
});
$run->silenceErrorsInPaths('@^'.preg_quote(__FILE__, '@').'$@', E_USER_NOTICE);
trigger_error('Test', E_USER_NOTICE);
$this->assertTrue(true);
}
/**
* @covers Whoops\Run::handleError
* @requires PHP < 8
*/
public function testGetSilencedError()
{
$run = $this->getRunInstance();
$run->register();
$handler = $this->getHandler();
$run->pushHandler($handler);
@strpos();
$error = error_get_last();
$this->assertTrue($error && strpos($error['message'], 'strpos()') !== false);
}
/**
* @covers Whoops\Run::handleError
* @see https://github.com/filp/whoops/issues/267
*/
public function testErrorWrappedInException()
{
try {
$run = $this->getRunInstance();
$run->handleError(E_WARNING, 'my message', 'my file', 99);
$this->fail("missing expected exception");
} catch (\ErrorException $e) {
$this->assertSame(E_WARNING, $e->getSeverity());
$this->assertSame(E_WARNING, $e->getCode(), "For BC reasons getCode() should match getSeverity()");
$this->assertSame('my message', $e->getMessage());
$this->assertSame('my file', $e->getFile());
$this->assertSame(99, $e->getLine());
}
}
/**
* @covers Whoops\Run::handleException
* @covers Whoops\Run::writeToOutput
*/
public function testOutputIsSent()
{
$run = $this->getRunInstance();
$run->pushHandler(function () {
echo "hello there";
});
ob_start();
$run->handleException(new RuntimeException());
$this->assertEquals("hello there", ob_get_clean());
}
/**
* @covers Whoops\Run::handleException
* @covers Whoops\Run::writeToOutput
*/
public function testOutputIsNotSent()
{
$run = $this->getRunInstance();
$run->writeToOutput(false);
$run->pushHandler(function () {
echo "hello there";
});
ob_start();
$this->assertEquals("hello there", $run->handleException(new RuntimeException()));
$this->assertEquals("", ob_get_clean());
}
/**
* @covers Whoops\Run::sendHttpCode
*/
public function testSendHttpCode()
{
$run = $this->getRunInstance();
$run->sendHttpCode(true);
$this->assertEquals(500, $run->sendHttpCode());
}
/**
* @covers Whoops\Run::sendHttpCode
*/
public function testSendHttpCodeNullCode()
{
$run = $this->getRunInstance();
$this->assertEquals(false, $run->sendHttpCode(null));
}
/**
* @covers Whoops\Run::sendHttpCode
*/
public function testSendHttpCodeWrongCode()
{
$this->expectExceptionOfType('InvalidArgumentException');
$this->getRunInstance()->sendHttpCode(1337);
}
/**
* @covers Whoops\Run::sendHttpCode
*/
public function testSendExitCode()
{
$run = $this->getRunInstance();
$run->sendExitCode(42);
$this->assertEquals(42, $run->sendExitCode());
}
/**
* @covers Whoops\Run::sendExitCode
*/
public function testSendExitCodeDefaultCode()
{
$run = $this->getRunInstance();
$this->assertEquals(1, $run->sendExitCode());
}
/**
* @covers Whoops\Run::sendExitCode
*/
public function testSendExitCodeWrongCode()
{
$this->expectExceptionOfType('InvalidArgumentException');
$this->getRunInstance()->sendExitCode(255);
}
/**
* @covers Whoops\Run::addFrameFilter
* @covers Whoops\Run::getFrameFilters
*/
public function testAddFrameFilter()
{
$run = $this->getRunInstance();
$filterCallbackOne = function(Frame $frame) {};
$filterCallbackTwo = function(Frame $frame) {};
$run
->addFrameFilter($filterCallbackOne)
->addFrameFilter($filterCallbackTwo);
$frameFilters = $run->getFrameFilters();
$this->assertCount(2, $frameFilters);
$this->assertContains($filterCallbackOne, $frameFilters);
$this->assertContains($filterCallbackTwo, $frameFilters);
$this->assertInstanceOf("Whoops\\RunInterface", $run);
}
/**
* @covers Whoops\Run::clearFrameFilters
* @covers Whoops\Run::getFrameFilters
*/
public function testClearFrameFilters()
{
$run = $this->getRunInstance();
$run->addFrameFilter(function(Frame $frame) {});
$run = $run->clearFrameFilters();
$this->assertEmpty($run->getFrameFilters());
$this->assertInstanceOf("Whoops\\RunInterface", $run);
}
public function testShutdownHandlerDoesNotRunIfUnregistered()
{
$system = m::mock('Whoops\Util\SystemFacade');
$run = new Run($system);
$run->writeToOutput(false);
$run->allowQuit(false);
$fatalError = [
'type' => E_ERROR,
'message' => 'Simulated fatal error for shutdown',
'file' => 'somefile.php',
'line' => 10,
];
$system->shouldReceive('getLastError')->andReturn($fatalError)->byDefault();
$mockHandler = m::mock('Whoops\Handler\HandlerInterface');
$mockHandler->shouldNotReceive('handle');
$mockHandler->shouldNotReceive('setRun');
$mockHandler->shouldNotReceive('setInspector');
$mockHandler->shouldNotReceive('setException');
$run->pushHandler($mockHandler);
$run->unregister();
ob_start();
$run->handleShutdown();
$output = ob_get_clean();
$this->assertEquals('', $output, "Output buffer should be empty.");
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Handler/JsonResponseHandlerTest.php | tests/Whoops/Handler/JsonResponseHandlerTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Handler;
use RuntimeException;
use Whoops\TestCase;
class JsonResponseHandlerTest extends TestCase
{
/**
* @return \Whoops\Handler\JsonResponseHandler
*/
private function getHandler()
{
return new JsonResponseHandler();
}
/**
* @return RuntimeException
*/
public function getException($message = 'test message')
{
return new RuntimeException($message);
}
/**
* @param bool $withTrace
* @return array
*/
private function getJsonResponseFromHandler($withTrace = false, $jsonApi = false)
{
$handler = $this->getHandler();
$handler->setJsonApi($jsonApi);
$handler->addTraceToOutput($withTrace);
$run = $this->getRunInstance();
$run->pushHandler($handler);
$run->register();
$exception = $this->getException();
ob_start();
$run->handleException($exception);
$json = json_decode(ob_get_clean(), true);
// Check that the json response is parse-able:
$this->assertEquals(json_last_error(), JSON_ERROR_NONE);
return $json;
}
/**
* @covers Whoops\Handler\JsonResponseHandler::addTraceToOutput
* @covers Whoops\Handler\JsonResponseHandler::handle
*/
public function testReturnsWithoutFrames()
{
$json = $this->getJsonResponseFromHandler($withTrace = false,$jsonApi = false);
// Check that the response has the expected keys:
$this->assertArrayHasKey('error', $json);
$this->assertArrayHasKey('type', $json['error']);
$this->assertArrayHasKey('file', $json['error']);
$this->assertArrayHasKey('line', $json['error']);
// Check the field values:
$this->assertEquals($json['error']['file'], __FILE__);
$this->assertEquals($json['error']['message'], 'test message');
$this->assertEquals($json['error']['type'], get_class($this->getException()));
// Check that the trace is NOT returned:
$this->assertArrayNotHasKey('trace', $json['error']);
}
/**
* @covers Whoops\Handler\JsonResponseHandler::addTraceToOutput
* @covers Whoops\Handler\JsonResponseHandler::handle
*/
public function testReturnsWithFrames()
{
$json = $this->getJsonResponseFromHandler($withTrace = true,$jsonApi = false);
// Check that the trace is returned:
$this->assertArrayHasKey('trace', $json['error']);
// Check that a random frame has the expected fields
$traceFrame = reset($json['error']['trace']);
$this->assertArrayHasKey('file', $traceFrame);
$this->assertArrayHasKey('line', $traceFrame);
$this->assertArrayHasKey('function', $traceFrame);
$this->assertArrayHasKey('class', $traceFrame);
$this->assertArrayHasKey('args', $traceFrame);
}
/**
* @covers Whoops\Handler\JsonResponseHandler::addTraceToOutput
* @covers Whoops\Handler\JsonResponseHandler::handle
*/
public function testReturnsJsonApi()
{
$json = $this->getJsonResponseFromHandler($withTrace = false,$jsonApi = true);
// Check that the response has the expected keys:
$this->assertArrayHasKey('errors', $json);
$this->assertArrayHasKey('type', $json['errors'][0]);
$this->assertArrayHasKey('file', $json['errors'][0]);
$this->assertArrayHasKey('line', $json['errors'][0]);
// Check the field values:
$this->assertEquals($json['errors'][0]['file'], __FILE__);
$this->assertEquals($json['errors'][0]['message'], 'test message');
$this->assertEquals($json['errors'][0]['type'], get_class($this->getException()));
// Check that the trace is NOT returned:
$this->assertArrayNotHasKey('trace', $json['errors']);
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Handler/PlainTextHandlerTest.php | tests/Whoops/Handler/PlainTextHandlerTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Handler;
use RuntimeException;
use StdClass;
use Whoops\TestCase;
use Whoops\Exception\Frame;
class PlainTextHandlerTest extends TestCase
{
const DEFAULT_EXCEPTION_LINE = 34;
const DEFAULT_LINE_OF_CALLER = 65;
/**
* @throws \InvalidArgumentException If argument is not null or a LoggerInterface
* @param \Psr\Log\LoggerInterface|null $logger
* @return \Whoops\Handler\PlainTextHandler
*/
private function getHandler($logger = null)
{
return new PlainTextHandler($logger);
}
/**
* @return RuntimeException
*/
public function getException($message = 'test message')
{
return new RuntimeException($message);
}
/**
* @param bool $withTrace
* @param bool $withTraceArgs
* @param int $traceFunctionArgsOutputLimit
* @param bool $loggerOnly
* @param bool $previousOutput
* @param null $exception
* @return array
*/
private function getPlainTextFromHandler(
$withTrace = false,
$withTraceArgs = false,
$traceFunctionArgsOutputLimit = 1024,
$loggerOnly = false,
$previousOutput = false,
$exception = null
) {
$handler = $this->getHandler();
$handler->addTraceToOutput($withTrace);
$handler->addTraceFunctionArgsToOutput($withTraceArgs);
$handler->setTraceFunctionArgsOutputLimit($traceFunctionArgsOutputLimit);
$handler->addPreviousToOutput($previousOutput);
$handler->loggerOnly($loggerOnly);
$run = $this->getRunInstance();
$run->pushHandler($handler);
$run->register();
$exception = $exception ?: $this->getException();
try {
ob_start();
$run->handleException($exception);
} finally {
return ob_get_clean();
}
}
/**
* @covers Whoops\Handler\PlainTextHandler::__construct
* @covers Whoops\Handler\PlainTextHandler::setLogger
*/
public function testConstructor()
{
$this->expectExceptionOfType('InvalidArgumentException');
$this->getHandler(new StdClass());
}
/**
* @covers Whoops\Handler\PlainTextHandler::setLogger
*/
public function testSetLogger()
{
$this->expectExceptionOfType('InvalidArgumentException');
$this->getHandler()->setLogger(new StdClass());
}
/**
* @covers Whoops\Handler\PlainTextHandler::addTraceToOutput
*/
public function testAddTraceToOutput()
{
$handler = $this->getHandler();
$this->assertEquals($handler, $handler->addTraceToOutput(true));
$this->assertTrue($handler->addTraceToOutput());
$handler->addTraceToOutput(false);
$this->assertFalse($handler->addTraceToOutput());
$handler->addTraceToOutput(null);
$this->assertEquals(null, $handler->addTraceToOutput());
$handler->addTraceToOutput(1);
$this->assertTrue($handler->addTraceToOutput());
$handler->addTraceToOutput(0);
$this->assertFalse($handler->addTraceToOutput());
$handler->addTraceToOutput('');
$this->assertFalse($handler->addTraceToOutput());
$handler->addTraceToOutput('false');
$this->assertTrue($handler->addTraceToOutput());
}
/**
* @covers Whoops\Handler\PlainTextHandler::addTraceFunctionArgsToOutput
*/
public function testAddTraceFunctionArgsToOutput()
{
$handler = $this->getHandler();
$this->assertEquals($handler, $handler->addTraceFunctionArgsToOutput(true));
$this->assertTrue($handler->addTraceFunctionArgsToOutput());
$handler->addTraceFunctionArgsToOutput(false);
$this->assertFalse($handler->addTraceFunctionArgsToOutput());
$handler->addTraceFunctionArgsToOutput(null);
$this->assertEquals(null, $handler->addTraceFunctionArgsToOutput());
$handler->addTraceFunctionArgsToOutput(1);
$this->assertEquals(1, $handler->addTraceFunctionArgsToOutput());
$handler->addTraceFunctionArgsToOutput(0);
$this->assertEquals(0, $handler->addTraceFunctionArgsToOutput());
$handler->addTraceFunctionArgsToOutput('');
$this->assertFalse($handler->addTraceFunctionArgsToOutput());
$handler->addTraceFunctionArgsToOutput('false');
$this->assertTrue($handler->addTraceFunctionArgsToOutput());
}
/**
* @covers Whoops\Handler\PlainTextHandler::setTraceFunctionArgsOutputLimit
* @covers Whoops\Handler\PlainTextHandler::getTraceFunctionArgsOutputLimit
*/
public function testGetSetTraceFunctionArgsOutputLimit()
{
$addTraceFunctionArgsToOutput = 10240;
$handler = $this->getHandler();
$handler->setTraceFunctionArgsOutputLimit($addTraceFunctionArgsToOutput);
$this->assertEquals($addTraceFunctionArgsToOutput, $handler->getTraceFunctionArgsOutputLimit());
$handler->setTraceFunctionArgsOutputLimit('1024kB');
$this->assertEquals(1024, $handler->getTraceFunctionArgsOutputLimit());
$handler->setTraceFunctionArgsOutputLimit('true');
$this->assertEquals(0, $handler->getTraceFunctionArgsOutputLimit());
}
/**
* @covers Whoops\Handler\PlainTextHandler::loggerOnly
*/
public function testLoggerOnly()
{
$handler = $this->getHandler();
$this->assertEquals($handler, $handler->loggerOnly(true));
$this->assertTrue($handler->loggerOnly());
$handler->loggerOnly(false);
$this->assertFalse($handler->loggerOnly());
$handler->loggerOnly(null);
$this->assertEquals(null, $handler->loggerOnly());
$handler->loggerOnly(1);
$this->assertTrue($handler->loggerOnly());
$handler->loggerOnly(0);
$this->assertFalse($handler->loggerOnly());
$handler->loggerOnly('');
$this->assertFalse($handler->loggerOnly());
$handler->loggerOnly('false');
$this->assertTrue($handler->loggerOnly());
}
/**
* @covers Whoops\Handler\PlainTextHandler::addTraceToOutput
* @covers Whoops\Handler\PlainTextHandler::handle
*/
public function testReturnsWithoutFramesOutput()
{
$text = $this->getPlainTextFromHandler(
$withTrace = false,
$withTraceArgs = true,
$traceFunctionArgsOutputLimit = 1024,
$loggerOnly = false
);
// Check that the response has the correct value:
// Check that the trace is NOT returned:
$this->assertEquals(
sprintf(
"%s: %s in file %s on line %d\n",
get_class($this->getException()),
'test message',
__FILE__,
self::DEFAULT_EXCEPTION_LINE
),
$text
);
}
public function testReturnsWithoutPreviousExceptions()
{
$text = $this->getPlainTextFromHandler(
$withTrace = false,
$withTraceArgs = true,
$traceFunctionArgsOutputLimit = 1024,
$loggerOnly = false,
$previousOutput = false,
new RuntimeException('Outer exception message', 0, new RuntimeException('Inner exception message'))
);
// Check that the response does not contain Inner exception message:
$this->assertStringNotContains(
sprintf(
"%s: %s in file %s",
RuntimeException::class,
'Inner exception message',
__FILE__
),
$text
);
}
public function testReturnsWithPreviousExceptions()
{
$text = $this->getPlainTextFromHandler(
$withTrace = false,
$withTraceArgs = true,
$traceFunctionArgsOutputLimit = 1024,
$loggerOnly = false,
$previousOutput = true,
new RuntimeException('Outer exception message', 0, new RuntimeException('Inner exception message'))
);
// Check that the response has the correct message:
$this->assertEquals(
sprintf(
"%s: %s in file %s on line %d\n" .
"%s: %s in file %s on line %d\n",
RuntimeException::class,
'Outer exception message',
__FILE__,
261,
"\nCaused by\n" . RuntimeException::class,
'Inner exception message',
__FILE__,
261
),
$text
);
}
/**
* @covers Whoops\Handler\PlainTextHandler::addTraceToOutput
* @covers Whoops\Handler\PlainTextHandler::getTraceOutput
* @covers Whoops\Handler\PlainTextHandler::canOutput
* @covers Whoops\Handler\PlainTextHandler::handle
*/
public function testReturnsWithFramesOutput()
{
$text = $this->getPlainTextFromHandler(
$withTrace = true,
$withTraceArgs = false,
$traceFunctionArgsOutputLimit = 1024,
$loggerOnly = false
);
// Check that the response has the correct value:
$this->assertStringContains('Stack trace:', $text);
// Check that the trace is returned:
$this->assertStringContains(
sprintf(
'%3d. %s->%s() %s:%d',
2,
__CLASS__,
'getException',
__FILE__,
self::DEFAULT_LINE_OF_CALLER
),
$text
);
}
/**
* @covers Whoops\Handler\PlainTextHandler::addTraceToOutput
* @covers Whoops\Handler\PlainTextHandler::addTraceFunctionArgsToOutput
* @covers Whoops\Handler\PlainTextHandler::getTraceOutput
* @covers Whoops\Handler\PlainTextHandler::getFrameArgsOutput
* @covers Whoops\Handler\PlainTextHandler::canOutput
* @covers Whoops\Handler\PlainTextHandler::handle
*/
public function testReturnsWithFramesAndArgsOutput()
{
$text = $this->getPlainTextFromHandler(
$withTrace = true,
$withTraceArgs = true,
$traceFunctionArgsOutputLimit = 2048,
$loggerOnly = false
);
$lines = explode("\n", $text);
// Check that the trace is returned with all arguments:
$this->assertGreaterThan(60, count($lines));
// Check that the response has the correct value:
$this->assertStringContains('Stack trace:', $text);
// Check that the trace is returned:
$this->assertStringContains(
sprintf(
'%3d. %s->%s() %s:%d',
2,
'Whoops\Handler\PlainTextHandlerTest',
'getException',
__FILE__,
self::DEFAULT_LINE_OF_CALLER
),
$text
);
// Check that the trace arguments are returned:
$this->assertStringContains(sprintf(
'%s string(%d) "%s"',
PlainTextHandler::VAR_DUMP_PREFIX,
strlen('test message'),
'test message'
), $text
);
}
/**
* @covers Whoops\Handler\PlainTextHandler::addTraceToOutput
* @covers Whoops\Handler\PlainTextHandler::addTraceFunctionArgsToOutput
* @covers Whoops\Handler\PlainTextHandler::getTraceOutput
* @covers Whoops\Handler\PlainTextHandler::getFrameArgsOutput
* @covers Whoops\Handler\PlainTextHandler::canOutput
* @covers Whoops\Handler\PlainTextHandler::handle
*/
public function testReturnsWithFramesAndLimitedArgsOutput()
{
$text = $this->getPlainTextFromHandler(
$withTrace = true,
$withTraceArgs = 3,
$traceFunctionArgsOutputLimit = 1024,
$loggerOnly = false
);
// Check that the response has the correct value:
$this->assertStringContains('Stack trace:', $text);
// Check that the trace is returned:
$this->assertStringContains(
sprintf(
'%3d. %s->%s() %s:%d',
2,
'Whoops\Handler\PlainTextHandlerTest',
'getException',
__FILE__,
self::DEFAULT_LINE_OF_CALLER
),
$text
);
// Check that the trace arguments are returned:
$this->assertStringContains(sprintf(
'%s string(%d) "%s"',
PlainTextHandler::VAR_DUMP_PREFIX,
strlen('test message'),
'test message'
), $text
);
}
/**
* @covers Whoops\Handler\PlainTextHandler::loggerOnly
* @covers Whoops\Handler\PlainTextHandler::handle
*/
public function testReturnsWithLoggerOnlyOutput()
{
$text = $this->getPlainTextFromHandler(
$withTrace = true,
$withTraceArgs = true,
$traceFunctionArgsOutputLimit = 1024,
$loggerOnly = true
);
// Check that the response has the correct value:
$this->assertEquals('', $text);
}
/**
* @covers Whoops\Handler\PlainTextHandler::loggerOnly
* @covers Whoops\Handler\PlainTextHandler::handle
*/
public function testGetFrameArgsOutputUsesDumper()
{
$values = [];
$dumper = function ($var) use (&$values) {
$values[] = $var;
};
$handler = $this->getHandler();
$handler->setDumper($dumper);
$args = [
['foo', 'bar', 'buz'],
[1, 2, 'Fizz', 4, 'Buzz'],
];
$actual = self::callPrivateMethod($handler, 'dump', [new Frame(['args' => $args[0]])]);
$this->assertEquals('', $actual);
$this->assertCount(1, $values);
$this->assertEquals($args[0], $values[0]->getArgs());
$actual = self::callPrivateMethod($handler, 'dump', [new Frame(['args' => $args[1]])]);
$this->assertEquals('', $actual);
$this->assertCount(2, $values);
$this->assertEquals($args[1], $values[1]->getArgs());
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Handler/CallbackHandlerTest.php | tests/Whoops/Handler/CallbackHandlerTest.php | <?php
namespace Whoops\Handler;
use Whoops\TestCase;
class CallbackHandlerTest extends TestCase
{
public function testSimplifiedBacktrace()
{
$handler = new CallbackHandler(function ($exception, $inspector, $run) {
return debug_backtrace();
});
$backtrace = $handler->handle();
foreach ($backtrace as $frame) {
$this->assertStringNotContains('call_user_func', $frame['function']);
}
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Handler/PrettyPageHandlerTest.php | tests/Whoops/Handler/PrettyPageHandlerTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Handler;
use InvalidArgumentException;
use RuntimeException;
use Whoops\TestCase;
class PrettyPageHandlerTest extends TestCase
{
/**
* @return \Whoops\Handler\PrettyPageHandler
*/
private function getHandler()
{
$handler = new PrettyPageHandler();
$handler->handleUnconditionally();
return $handler;
}
/**
* @return RuntimeException
*/
public function getException()
{
return new RuntimeException();
}
/**
* Test that PrettyPageHandle handles the template without
* any errors.
* @covers Whoops\Handler\PrettyPageHandler::handle
*/
public function testHandleWithoutErrors()
{
$run = $this->getRunInstance();
$handler = $this->getHandler();
$run->pushHandler($handler);
ob_start();
$run->handleException($this->getException());
ob_get_clean();
// Reached the end without errors
$this->assertTrue(true);
}
/**
* @covers Whoops\Handler\PrettyPageHandler::setPageTitle
* @covers Whoops\Handler\PrettyPageHandler::getPageTitle
*/
public function testGetSetPageTitle()
{
$title = 'My Cool Error Handler';
$handler = $this->getHandler();
$this->assertEquals($handler, $handler->setPageTitle($title));
$this->assertEquals($title, $handler->getPagetitle());
}
/**
* @covers Whoops\Handler\PrettyPageHandler::addResourcePath
* @covers Whoops\Handler\PrettyPageHandler::getResourcePaths
*/
public function testGetSetResourcePaths()
{
$path = __DIR__; // guaranteed to be valid!
$handler = $this->getHandler();
$this->assertEquals($handler, $handler->addResourcePath($path));
$allPaths = $handler->getResourcePaths();
$this->assertCount(2, $allPaths);
$this->assertEquals($allPaths[0], $path);
}
/**
* @covers Whoops\Handler\PrettyPageHandler::addResourcePath
*/
public function testSetInvalidResourcesPath()
{
$this->expectExceptionOfType('InvalidArgumentException');
$this->getHandler()->addResourcePath(__DIR__ . '/ZIMBABWE');
}
/**
* @covers Whoops\Handler\PrettyPageHandler::getDataTables
* @covers Whoops\Handler\PrettyPageHandler::addDataTable
*/
public function testGetSetDataTables()
{
$handler = $this->getHandler();
// should have no tables by default:
$this->assertEmpty($handler->getDataTables());
$tableOne = [
'ice' => 'cream',
'ice-ice' => 'baby',
];
$tableTwo = [
'dolan' => 'pls',
'time' => time(),
];
$this->assertEquals($handler, $handler->addDataTable('table 1', $tableOne));
$this->assertEquals($handler, $handler->addDataTable('table 2', $tableTwo));
// should contain both tables:
$tables = $handler->getDataTables();
$this->assertCount(2, $tables);
$this->assertEquals($tableOne, $tables['table 1']);
$this->assertEquals($tableTwo, $tables['table 2']);
// should contain only table 1
$this->assertEquals($tableOne, $handler->getDataTables('table 1'));
// should return an empty table:
$this->assertEmpty($handler->getDataTables('ZIMBABWE!'));
}
/**
* @covers Whoops\Handler\PrettyPageHandler::getDataTables
* @covers Whoops\Handler\PrettyPageHandler::addDataTableCallback
*/
public function testSetCallbackDataTables()
{
$handler = $this->getHandler();
$this->assertEmpty($handler->getDataTables());
$table1 = function () {
return [
'hammer' => 'time',
'foo' => 'bar',
];
};
$expected1 = ['hammer' => 'time', 'foo' => 'bar'];
$table2 = function () use ($expected1) {
return [
'another' => 'table',
'this' => $expected1,
];
};
$expected2 = ['another' => 'table', 'this' => $expected1];
$table3 = function() {
return array("oh my" => "how times have changed!");
};
$expected3 = ['oh my' => 'how times have changed!'];
// Test inspector parameter in data table callback
$table4 = function (\Whoops\Exception\Inspector $inspector) {
return array(
'Exception class' => get_class($inspector->getException()),
'Exception message' => $inspector->getExceptionMessage(),
);
};
$expected4 = array(
'Exception class' => 'InvalidArgumentException',
'Exception message' => 'Test exception message',
);
$inspectorForTable4 = new \Whoops\Exception\Inspector(
new \InvalidArgumentException('Test exception message')
);
// Sanity check, make sure expected values really are correct.
$this->assertSame($expected1, $table1());
$this->assertSame($expected2, $table2());
$this->assertSame($expected3, $table3());
$this->assertSame($expected4, $table4($inspectorForTable4));
$this->assertEquals($handler, $handler->addDataTableCallback('table1', $table1));
$this->assertEquals($handler, $handler->addDataTableCallback('table2', $table2));
$this->assertEquals($handler, $handler->addDataTableCallback('table3', $table3));
$this->assertEquals($handler, $handler->addDataTableCallback('table4', $table4));
$tables = $handler->getDataTables();
$this->assertCount(4, $tables);
// Supplied callable is wrapped in a closure
$this->assertInstanceOf('Closure', $tables['table1']);
$this->assertInstanceOf('Closure', $tables['table2']);
$this->assertInstanceOf('Closure', $tables['table3']);
$this->assertInstanceOf('Closure', $tables['table4']);
// Run each wrapped callable and check results against expected output.
$this->assertEquals($expected1, $tables['table1']());
$this->assertEquals($expected2, $tables['table2']());
$this->assertEquals($expected3, $tables['table3']());
$this->assertEquals($expected4, $tables['table4']($inspectorForTable4));
$this->assertSame($tables['table1'], $handler->getDataTables('table1'));
$this->assertSame($expected1, call_user_func($handler->getDataTables('table1')));
}
/**
* @covers Whoops\Handler\PrettyPageHandler::setEditor
* @covers Whoops\Handler\PrettyPageHandler::getEditorHref
*/
public function testSetEditorSimple()
{
$handler = $this->getHandler();
$this->assertEquals($handler, $handler->setEditor('sublime'));
$this->assertEquals(
$handler->getEditorHref('/foo/bar.php', 10),
'subl://open?url=file://%2Ffoo%2Fbar.php&line=10'
);
$this->assertEquals(
$handler->getEditorHref('/foo/with space?.php', 2324),
'subl://open?url=file://%2Ffoo%2Fwith%20space%3F.php&line=2324'
);
$this->assertEquals(
$handler->getEditorHref('/foo/bar/with-dash.php', 0),
'subl://open?url=file://%2Ffoo%2Fbar%2Fwith-dash.php&line=0'
);
}
/**
* @covers Whoops\Handler\PrettyPageHandler::setEditor
* @covers Whoops\Handler\PrettyPageHandler::getEditorHref
* @covers Whoops\Handler\PrettyPageHandler::getEditorAjax
*/
public function testSetEditorCallable()
{
$handler = $this->getHandler();
// Test Callable editor with String return
$this->assertEquals($handler, $handler->setEditor(function ($file, $line) {
$file = rawurlencode($file);
$line = rawurlencode($line);
return "http://google.com/search/?q=$file:$line";
}));
$this->assertEquals(
$handler->getEditorHref('/foo/bar.php', 10),
'http://google.com/search/?q=%2Ffoo%2Fbar.php:10'
);
// Then test Callable editor with Array return
$this->assertEquals($handler, $handler->setEditor(function ($file, $line) {
$file = rawurlencode($file);
$line = rawurlencode($line);
return [
'url' => "http://google.com/search/?q=$file:$line",
'ajax' => true,
];
}));
$this->assertEquals(
$handler->getEditorHref('/foo/bar.php', 10),
'http://google.com/search/?q=%2Ffoo%2Fbar.php:10'
);
$this->assertEquals(
$handler->getEditorAjax('/foo/bar.php', 10),
true
);
$this->assertEquals($handler, $handler->setEditor(function ($file, $line) {
$file = rawurlencode($file);
$line = rawurlencode($line);
return [
'url' => "http://google.com/search/?q=$file:$line",
'ajax' => false,
];
}));
$this->assertEquals(
$handler->getEditorHref('/foo/bar.php', 10),
'http://google.com/search/?q=%2Ffoo%2Fbar.php:10'
);
$this->assertEquals(
$handler->getEditorAjax('/foo/bar.php', 10),
false
);
$this->assertEquals($handler, $handler->setEditor(function ($file, $line) {
return false;
}));
$this->assertEquals(
$handler->getEditorHref('/foo/bar.php', 10),
false
);
}
/**
* @covers Whoops\Handler\PrettyPageHandler::setEditor
* @covers Whoops\Handler\PrettyPageHandler::addEditor
* @covers Whoops\Handler\PrettyPageHandler::getEditorHref
*/
public function testAddEditor()
{
$handler = $this->getHandler();
$this->assertEquals($handler, $handler->addEditor('test-editor',
function ($file, $line) {
return "cool beans $file:$line";
}));
$this->assertEquals($handler, $handler->setEditor('test-editor'));
$this->assertEquals(
$handler->getEditorHref('hello', 20),
'cool beans hello:20'
);
}
public function testEditorXdebug()
{
if (!extension_loaded('xdebug')) {
// Even though this test only uses ini_set and ini_get,
// without xdebug active, those calls do not work.
// In particular, ini_get after ini_setting returns false.
$this->markTestSkipped('The xdebug extension is not loaded.');
}
$originalValue = ini_get('xdebug.file_link_format');
ini_set('xdebug.file_link_format', '%f:%l');
$handler = $this->getHandler();
$this->assertEquals($handler, $handler->setEditor('xdebug'));
$this->assertEquals(
'/foo/bar.php:10',
$handler->getEditorHref('/foo/bar.php', 10)
);
ini_set('xdebug.file_link_format', 'subl://open?url=%f&line=%l');
// xdebug doesn't do any URL encoded, matching that behaviour.
$this->assertEquals(
'subl://open?url=/foo/with space?.php&line=2324',
$handler->getEditorHref('/foo/with space?.php', 2324)
);
ini_set('xdebug.file_link_format', $originalValue);
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Handler/XmlResponseHandlerTest.php | tests/Whoops/Handler/XmlResponseHandlerTest.php | <?php
/**
* Whoops - php errors for cool kids
*/
namespace Whoops\Handler;
use RuntimeException;
use Whoops\TestCase;
class XmlResponseHandlerTest extends TestCase
{
public function testSimpleValid()
{
$handler = new XmlResponseHandler();
$run = $this->getRunInstance();
$run->pushHandler($handler);
$run->register();
ob_start();
$run->handleException($this->getException());
$data = ob_get_clean();
$this->assertTrue($this->isValidXml($data));
return simplexml_load_string($data);
}
/**
* @depends testSimpleValid
*/
public function testSimpleValidFile(\SimpleXMLElement $xml)
{
$this->checkField($xml, 'file', $this->getException()->getFile());
}
/**
* @depends testSimpleValid
*/
public function testSimpleValidLine(\SimpleXMLElement $xml)
{
$this->checkField($xml, 'line', (string) $this->getException()->getLine());
}
/**
* @depends testSimpleValid
*/
public function testSimpleValidType(\SimpleXMLElement $xml)
{
$this->checkField($xml, 'type', get_class($this->getException()));
}
/**
* Helper for testSimpleValid*
*/
private function checkField(\SimpleXMLElement $xml, $field, $value)
{
$list = $xml->xpath('/root/error/'.$field);
$this->assertArrayHasKey(0, $list);
$this->assertSame($value, (string) $list[0]);
}
private function getException()
{
return new RuntimeException();
}
/**
* See if passed string is a valid XML document
* @param string $data
* @return bool
*/
private function isValidXml($data)
{
$prev = libxml_use_internal_errors(true);
$xml = simplexml_load_string($data);
libxml_use_internal_errors($prev);
return $xml !== false;
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Util/MiscTest.php | tests/Whoops/Util/MiscTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Util;
use Whoops\TestCase;
class MiscTest extends TestCase
{
/**
* @dataProvider provideTranslateException
* @param string $expected_output
* @param int $exception_code
*/
public function testTranslateException($expected_output, $exception_code)
{
$output = Misc::translateErrorCode($exception_code);
$this->assertEquals($expected_output, $output);
}
public function provideTranslateException()
{
return [
// When passing an error constant value, ensure the error constant
// is returned.
['E_USER_WARNING', E_USER_WARNING],
// When passing a value not equal to an error constant, ensure
// E_UNKNOWN is returned.
['E_UNKNOWN', 3],
];
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Util/SystemFacadeTest.php | tests/Whoops/Util/SystemFacadeTest.php | <?php
namespace Whoops\Util;
use PHPUnit\Framework\TestCase;
class SystemFacadeTest extends TestCase
{
/**
* @var \Mockery\Mock
*/
public static $runtime;
/**
* @var SystemFacade
*/
private $facade;
public static function delegate($fn, array $args = [])
{
return self::$runtime
? call_user_func_array([self::$runtime, $fn], $args)
: call_user_func_array("\\$fn", $args);
}
/**
* @before
*/
public function getReady()
{
self::$runtime = \Mockery::mock(['ob_start' => true]);
$this->facade = new SystemFacade();
}
/**
* @after
*/
public function finishUp()
{
self::$runtime = null;
\Mockery::close();
}
public function test_it_delegates_output_buffering_to_the_native_implementation()
{
self::$runtime->shouldReceive('ob_start')->once();
$this->facade->startOutputBuffering();
}
public function test_it_delegates_cleaning_output_buffering_to_the_native_implementation()
{
self::$runtime->shouldReceive('ob_get_clean')->once();
$this->facade->cleanOutputBuffer();
}
public function test_it_delegates_getting_the_current_buffer_level_to_the_native_implementation()
{
self::$runtime->shouldReceive('ob_get_level')->once();
$this->facade->getOutputBufferLevel();
}
public function test_it_delegates_ending_the_current_buffer_to_the_native_implementation()
{
self::$runtime->shouldReceive('ob_end_clean')->once();
$this->facade->endOutputBuffering();
}
public function test_it_delegates_flushing_the_current_buffer_to_the_native_implementation()
{
self::$runtime->shouldReceive('flush')->once();
$this->facade->flushOutputBuffer();
}
public function test_it_delegates_error_handling_to_the_native_implementation()
{
self::$runtime->shouldReceive('set_error_handler')->once();
$this->facade->setErrorHandler(function(){});
}
public function test_it_delegates_error_handling_with_level_to_the_native_implementation()
{
self::$runtime->shouldReceive('set_error_handler')->once();
$this->facade->setErrorHandler(function(){}, E_CORE_ERROR);
}
public function test_it_delegates_exception_handling_to_the_native_implementation()
{
self::$runtime->shouldReceive('set_exception_handler')->once();
$this->facade->setExceptionHandler(function(){});
}
public function test_it_delegates_restoring_the_exception_handler_to_the_native_implementation()
{
self::$runtime->shouldReceive('restore_exception_handler')->once();
$this->facade->restoreExceptionHandler();
}
public function test_it_delegates_restoring_the_error_handler_to_the_native_implementation()
{
self::$runtime->shouldReceive('restore_error_handler')->once();
$this->facade->restoreErrorHandler();
}
public function test_it_delegates_registering_a_shutdown_function_to_the_native_implementation()
{
self::$runtime->shouldReceive('register_shutdown_function')->once();
$this->facade->registerShutdownFunction(function(){});
}
public function test_it_delegates_error_reporting_to_the_native_implementation()
{
self::$runtime->shouldReceive('error_reporting')->once()->withNoArgs();
$this->facade->getErrorReportingLevel();
}
public function test_it_delegates_getting_the_last_error_to_the_native_implementation()
{
self::$runtime->shouldReceive('error_get_last')->once()->withNoArgs();
$this->facade->getLastError();
}
public function test_it_delegates_sending_an_http_response_code_to_the_native_implementation()
{
self::$runtime->shouldReceive('headers_sent')->once()->withNoArgs();
self::$runtime->shouldReceive('header_remove')->once()->with('location');
self::$runtime->shouldReceive('http_response_code')->once()->with(230);
$this->facade->setHttpResponseCode(230);
}
}
function ob_start()
{
return SystemFacadeTest::delegate('ob_start');
}
function ob_get_clean()
{
return SystemFacadeTest::delegate('ob_get_clean');
}
function ob_get_level()
{
return SystemFacadeTest::delegate('ob_get_level');
}
function ob_end_clean()
{
return SystemFacadeTest::delegate('ob_end_clean');
}
function flush()
{
return SystemFacadeTest::delegate('flush');
}
function set_error_handler(callable $handler, $types = 'use-php-defaults')
{
// Workaround for PHP 5.5
if ($types === 'use-php-defaults') {
$types = E_ALL | E_STRICT;
}
return SystemFacadeTest::delegate('set_error_handler', func_get_args());
}
function set_exception_handler(callable $handler)
{
return SystemFacadeTest::delegate('set_exception_handler', func_get_args());
}
function restore_exception_handler()
{
return SystemFacadeTest::delegate('restore_exception_handler');
}
function restore_error_handler()
{
return SystemFacadeTest::delegate('restore_error_handler');
}
function register_shutdown_function()
{
return SystemFacadeTest::delegate('register_shutdown_function', func_get_args());
}
function error_reporting($level = null)
{
return SystemFacadeTest::delegate('error_reporting', func_get_args());
}
function error_get_last()
{
return SystemFacadeTest::delegate('error_get_last', func_get_args());
}
function header_remove($header = null)
{
return SystemFacadeTest::delegate('header_remove', func_get_args());
}
function headers_sent(&$filename = null, &$line = null)
{
return SystemFacadeTest::delegate('headers_sent', func_get_args());
}
function http_response_code($code = null)
{
return SystemFacadeTest::delegate('http_response_code', func_get_args());
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Util/TemplateHelperTest.php | tests/Whoops/Util/TemplateHelperTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Util;
use Whoops\TestCase;
class TemplateHelperTest extends TestCase
{
/**
* @var TemplateHelper
*/
private $helper;
/**
* @before
*/
public function getReady()
{
$this->helper = new TemplateHelper();
}
/**
* @covers Whoops\Util\TemplateHelper::escapeButPreserveUris
* @covers Whoops\Util\TemplateHelper::escape
*/
public function testEscape()
{
$original = "This is a <a href=''>Foo</a> test string";
$this->assertEquals(
$this->helper->escape($original),
"This is a <a href=''>Foo</a> test string"
);
}
public function testEscapeBrokenUtf8()
{
// The following includes an illegal utf-8 sequence to test.
// Encoded in base64 to survive possible encoding changes of this file.
$original = base64_decode('VGhpcyBpcyBhbiBpbGxlZ2FsIHV0Zi04IHNlcXVlbmNlOiDD');
// Test that the escaped string is kinda similar in length, not empty
$this->assertLessThan(
10,
abs(strlen($original) - strlen($this->helper->escape($original)))
);
}
/**
* @covers Whoops\Util\TemplateHelper::escapeButPreserveUris
*/
public function testEscapeButPreserveUris()
{
$original = "This is a <a href=''>http://google.com</a> test string";
$this->assertEquals(
$this->helper->escapeButPreserveUris($original),
"This is a <a href=''><a href=\"http://google.com\" target=\"_blank\" rel=\"noreferrer noopener\">http://google.com</a></a> test string"
);
}
/**
* @covers Whoops\Util\TemplateHelper::breakOnDelimiter
*/
public function testBreakOnDelimiter()
{
$this->assertSame(
'<span class="delimiter">abc</span>-<span class="delimiter">123</span>-<span class="delimiter">456</span>',
$this->helper->breakOnDelimiter('-', 'abc-123-456')
);
}
/**
* @covers Whoops\Util\TemplateHelper::shorten
*/
public function testShorten()
{
$path = '/foo/bar/baz/abc.def';
$this->assertSame($path, $this->helper->shorten($path));
$this->helper->setApplicationRootPath('/foo/bar');
$this->assertSame('…/baz/abc.def', $this->helper->shorten($path));
}
/**
* @covers Whoops\Util\TemplateHelper::slug
*/
public function testSlug()
{
$this->assertEquals("hello-world", $this->helper->slug("Hello, world!"));
$this->assertEquals("potato-class", $this->helper->slug("Potato class"));
}
/**
* @covers Whoops\Util\TemplateHelper::render
*/
public function testRender()
{
$template = __DIR__ . "/../../fixtures/template.php";
ob_start();
$this->helper->render($template, ["name" => "B<o>b"]);
$output = ob_get_clean();
$this->assertEquals(
$output,
"hello-world\nMy name is B<o>b"
);
}
/**
* @covers Whoops\Util\TemplateHelper::setVariables
* @covers Whoops\Util\TemplateHelper::getVariables
* @covers Whoops\Util\TemplateHelper::setVariable
* @covers Whoops\Util\TemplateHelper::getVariable
* @covers Whoops\Util\TemplateHelper::delVariable
*/
public function testTemplateVariables()
{
$this->helper->setVariables([
"name" => "Whoops",
"type" => "library",
"desc" => "php errors for cool kids",
]);
$this->helper->setVariable("name", "Whoops!");
$this->assertEquals($this->helper->getVariable("name"), "Whoops!");
$this->helper->delVariable("type");
$this->assertEquals($this->helper->getVariables(), [
"name" => "Whoops!",
"desc" => "php errors for cool kids",
]);
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Util/HtmlDumperOutputTest.php | tests/Whoops/Util/HtmlDumperOutputTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Util;
use Whoops\TestCase;
class HtmlDumperOutputTest extends TestCase
{
/**
* @covers Whoops\Util::__invoke
* @covers Whoops\Util::getOutput
*/
public function testOutput()
{
$htmlDumperOutput = new HtmlDumperOutput();
$htmlDumperOutput('first line', 0);
$htmlDumperOutput('second line', 2);
$expectedOutput = <<<string
first line
second line
string;
$this->assertSame($expectedOutput, $htmlDumperOutput->getOutput());
}
/**
* @covers Whoops\Util::clear
*/
public function testClear()
{
$htmlDumperOutput = new HtmlDumperOutput();
$htmlDumperOutput('first line', 0);
$htmlDumperOutput('second line', 2);
$htmlDumperOutput->clear();
$this->assertNull($htmlDumperOutput->getOutput());
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Exception/FrameCollectionTest.php | tests/Whoops/Exception/FrameCollectionTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Exception;
use Whoops\TestCase;
class FrameCollectionTest extends TestCase
{
/**
* Stupid little counter for tagging frames
* with a unique but predictable id
* @var int
*/
private $frameIdCounter = 0;
/**
* @return array
*/
public function getFrameData()
{
$id = ++$this->frameIdCounter;
return [
'file' => __DIR__ . '/../../fixtures/frame.lines-test.php',
'line' => $id,
'function' => 'test-' . $id,
'class' => 'MyClass',
'args' => [true, 'hello'],
];
}
/**
* @param int $total
* @return array
*/
public function getFrameDataList($total)
{
$total = max((int) $total, 1);
$self = $this;
$frames = array_map(function () use ($self) {
return $self->getFrameData();
}, range(1, $total));
return $frames;
}
/**
* @param array $frames
* @return \Whoops\Exception\FrameCollection
*/
private function getFrameCollectionInstance($frames = null)
{
if ($frames === null) {
$frames = $this->getFrameDataList(10);
}
return new FrameCollection($frames);
}
/**
* @covers Whoops\Exception\FrameCollection::offsetExists
*/
public function testArrayAccessExists()
{
$collection = $this->getFrameCollectionInstance();
$this->assertArrayHasKey(0, $collection);
}
/**
* @covers Whoops\Exception\FrameCollection::offsetGet
*/
public function testArrayAccessGet()
{
$collection = $this->getFrameCollectionInstance();
$this->assertInstanceOf('Whoops\\Exception\\Frame', $collection[0]);
}
/**
* @covers Whoops\Exception\FrameCollection::offsetSet
*/
public function testArrayAccessSet()
{
$collection = $this->getFrameCollectionInstance();
$this->expectExceptionOfType('Exception');
$collection[0] = 'foo';
}
/**
* @covers Whoops\Exception\FrameCollection::offsetUnset
*/
public function testArrayAccessUnset()
{
$collection = $this->getFrameCollectionInstance();
$this->expectExceptionOfType('Exception');
unset($collection[0]);
}
/**
* @covers Whoops\Exception\FrameCollection::filter
* @covers Whoops\Exception\FrameCollection::count
*/
public function testFilterFrames()
{
$frames = $this->getFrameCollectionInstance();
// Filter out all frames with a line number under 6
$frames->filter(function ($frame) {
return $frame->getLine() <= 5;
});
$this->assertCount(5, $frames);
}
/**
* @covers Whoops\Exception\FrameCollection::map
*/
public function testMapFrames()
{
$frames = $this->getFrameCollectionInstance();
// Filter out all frames with a line number under 6
$frames->map(function ($frame) {
$frame->addComment("This is cool", "test");
return $frame;
});
$this->assertCount(10, $frames);
}
/**
* @covers Whoops\Exception\FrameCollection::map
*/
public function testMapFramesEnforceType()
{
$frames = $this->getFrameCollectionInstance();
$this->expectExceptionOfType('UnexpectedValueException');
// Filter out all frames with a line number under 6
$frames->map(function ($frame) {
return "bajango";
});
}
/**
* @covers Whoops\Exception\FrameCollection::getArray
*/
public function testGetArray()
{
$frames = $this->getFrameCollectionInstance();
$frames = $frames->getArray();
$this->assertCount(10, $frames);
foreach ($frames as $frame) {
$this->assertInstanceOf('Whoops\\Exception\\Frame', $frame);
}
}
/**
* @covers Whoops\Exception\FrameCollection::getArray
*/
public function testGetArrayImmutable()
{
$frames = $this->getFrameCollectionInstance();
$arr = $frames->getArray();
$arr[0] = 'foobar';
$newCopy = $frames->getArray();
$this->assertNotSame($arr[0], $newCopy);
}
/**
* @covers Whoops\Exception\FrameCollection::getIterator
*/
public function testCollectionIsIterable()
{
$frames = $this->getFrameCollectionInstance();
foreach ($frames as $frame) {
$this->assertInstanceOf('Whoops\\Exception\\Frame', $frame);
}
}
/**
* @covers Whoops\Exception\FrameCollection::serialize
* @covers Whoops\Exception\FrameCollection::unserialize
*/
public function testCollectionIsSerializable()
{
$frames = $this->getFrameCollectionInstance();
$serializedFrames = serialize($frames);
$newFrames = unserialize($serializedFrames);
foreach ($newFrames as $frame) {
$this->assertInstanceOf('Whoops\\Exception\\Frame', $frame);
}
}
/**
* @covers Whoops\Exception\FrameCollection::topDiff
*/
public function testTopDiff()
{
$commonFrameTail = $this->getFrameDataList(3);
$diffFrame = ['line' => $this->frameIdCounter] + $this->getFrameData();
$frameCollection1 = new FrameCollection(array_merge([
$diffFrame,
], $commonFrameTail));
$frameCollection2 = new FrameCollection(array_merge([
$this->getFrameData(),
], $commonFrameTail));
$diff = $frameCollection1->topDiff($frameCollection2);
$this->assertCount(1, $diff);
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Exception/FrameTest.php | tests/Whoops/Exception/FrameTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Exception;
use Whoops\TestCase;
class FrameTest extends TestCase
{
/**
* @return array
*/
private function getFrameData()
{
return [
'file' => __DIR__ . '/../../fixtures/frame.lines-test.php',
'line' => 0,
'function' => 'test',
'class' => 'MyClass',
'args' => [true, 'hello'],
];
}
/**
* @param array $data
* @return Frame
*/
private function getFrameInstance($data = null)
{
if ($data === null) {
$data = $this->getFrameData();
}
return new Frame($data);
}
/**
* @covers Whoops\Exception\Frame::getFile
*/
public function testGetFile()
{
$data = $this->getFrameData();
$frame = $this->getFrameInstance($data);
$this->assertEquals($frame->getFile(), $data['file']);
}
/**
* @covers Whoops\Exception\Frame::getLine
*/
public function testGetLine()
{
$data = $this->getFrameData();
$frame = $this->getFrameInstance($data);
$this->assertEquals($frame->getLine(), $data['line']);
}
/**
* @covers Whoops\Exception\Frame::getClass
*/
public function testGetClass()
{
$data = $this->getFrameData();
$frame = $this->getFrameInstance($data);
$this->assertEquals($frame->getClass(), $data['class']);
}
/**
* @covers Whoops\Exception\Frame::getFunction
*/
public function testGetFunction()
{
$data = $this->getFrameData();
$frame = $this->getFrameInstance($data);
$this->assertEquals($frame->getFunction(), $data['function']);
}
/**
* @covers Whoops\Exception\Frame::getArgs
*/
public function testGetArgs()
{
$data = $this->getFrameData();
$frame = $this->getFrameInstance($data);
$this->assertEquals($frame->getArgs(), $data['args']);
}
/**
* @covers Whoops\Exception\Frame::getFileContents
*/
public function testGetFileContents()
{
$data = $this->getFrameData();
$frame = $this->getFrameInstance($data);
$this->assertStringEqualsFile($data['file'], $frame->getFileContents());
}
/**
* @covers Whoops\Exception\Frame::getFileContents
* @testWith ["[internal]"]
* ["Unknown"]
* @see https://github.com/filp/whoops/pull/599
*/
public function testGetFileContentsWhenFrameIsNotRelatedToSpecificFile($fakeFilename)
{
$data = array_merge($this->getFrameData(), ['file' => $fakeFilename]);
$frame = $this->getFrameInstance($data);
$this->assertNull($frame->getFileContents());
}
/**
* @covers Whoops\Exception\Frame::getFileLines
*/
public function testGetFileLines()
{
$data = $this->getFrameData();
$frame = $this->getFrameInstance($data);
$lines = explode("\n", $frame->getFileContents());
$this->assertEquals($frame->getFileLines(), $lines);
}
/**
* @covers Whoops\Exception\Frame::getFileLines
*/
public function testGetFileLinesRange()
{
$data = $this->getFrameData();
$frame = $this->getFrameInstance($data);
$lines = $frame->getFileLines(0, 3);
$this->assertEquals($lines[0], '<?php');
$this->assertEquals($lines[1], '// Line 2');
$this->assertEquals($lines[2], '// Line 3');
}
/**
* @covers Whoops\Exception\Frame::addComment
* @covers Whoops\Exception\Frame::getComments
*/
public function testGetComments()
{
$frame = $this->getFrameInstance();
$testComments = [
'Dang, yo!',
'Errthangs broken!',
'Dayumm!',
];
$frame->addComment($testComments[0]);
$frame->addComment($testComments[1]);
$frame->addComment($testComments[2]);
$comments = $frame->getComments();
$this->assertCount(3, $comments);
$this->assertEquals($comments[0]['comment'], $testComments[0]);
$this->assertEquals($comments[1]['comment'], $testComments[1]);
$this->assertEquals($comments[2]['comment'], $testComments[2]);
}
/**
* @covers Whoops\Exception\Frame::addComment
* @covers Whoops\Exception\Frame::getComments
*/
public function testGetFilteredComments()
{
$frame = $this->getFrameInstance();
$testComments = [
['Dang, yo!', 'test'],
['Errthangs broken!', 'test'],
'Dayumm!',
];
$frame->addComment($testComments[0][0], $testComments[0][1]);
$frame->addComment($testComments[1][0], $testComments[1][1]);
$frame->addComment($testComments[2][0], $testComments[2][1]);
$comments = $frame->getComments('test');
$this->assertCount(2, $comments);
$this->assertEquals($comments[0]['comment'], $testComments[0][0]);
$this->assertEquals($comments[1]['comment'], $testComments[1][0]);
}
/**
* @covers Whoops\Exception\Frame::serialize
* @covers Whoops\Exception\Frame::unserialize
*/
public function testFrameIsSerializable()
{
$data = $this->getFrameData();
$frame = $this->getFrameInstance();
$commentText = "Gee I hope this works";
$commentContext = "test";
$frame->addComment($commentText, $commentContext);
$serializedFrame = serialize($frame);
$newFrame = unserialize($serializedFrame);
$this->assertInstanceOf('Whoops\\Exception\\Frame', $newFrame);
$this->assertEquals($newFrame->getFile(), $data['file']);
$this->assertEquals($newFrame->getLine(), $data['line']);
$comments = $newFrame->getComments();
$this->assertCount(1, $comments);
$this->assertEquals($comments[0]["comment"], $commentText);
$this->assertEquals($comments[0]["context"], $commentContext);
}
/**
* @covers Whoops\Exception\Frame::equals
*/
public function testEquals()
{
$frame1 = $this->getFrameInstance(['line' => 1, 'file' => 'test-file.php']);
$frame2 = $this->getFrameInstance(['line' => 1, 'file' => 'test-file.php']);
$this->assertTrue ($frame1->equals($frame2));
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Exception/FormatterTest.php | tests/Whoops/Exception/FormatterTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Exception;
use Whoops\TestCase;
class FormatterTest extends TestCase
{
public function testPlain()
{
$msg = 'Sample exception message foo';
$output = Formatter::formatExceptionPlain(new Inspector(new \Exception($msg)));
$this->assertStringContains($msg, $output);
$this->assertStringContains('Stacktrace', $output);
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/tests/Whoops/Exception/InspectorTest.php | tests/Whoops/Exception/InspectorTest.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
namespace Whoops\Exception;
use Exception;
use Whoops\TestCase;
class InspectorTest extends TestCase
{
/**
* @param string $message
* @param int $code
* @param Exception $previous
* @return Exception
*/
protected function getException($message = "", $code = 0, $previous = null)
{
return new Exception($message, $code, $previous);
}
/**
* @param Exception $exception|null
* @return \Whoops\Exception\Inspector
*/
protected function getInspectorInstance($exception = null)
{
return new Inspector($exception);
}
/**
* @covers Whoops\Exception\Inspector::getFrames
*/
public function testCorrectNestedFrames($value = '')
{
// Create manually to have a different line number from the outer
$inner = new Exception('inner');
$outer = $this->getException('outer', 0, $inner);
$inspector = $this->getInspectorInstance($outer);
$frames = $inspector->getFrames();
$this->assertSame($outer->getLine(), $frames[0]->getLine());
}
/**
* @covers Whoops\Exception\Inspector::getFrames
*/
public function testDoesNotFailOnPHP7ErrorObject()
{
if (!class_exists('Error')) {
$this->markTestSkipped(
'PHP 5.x, the Error class is not available.'
);
}
$inner = new \Error('inner');
$outer = $this->getException('outer', 0, $inner);
$inspector = $this->getInspectorInstance($outer);
$frames = $inspector->getFrames();
$this->assertSame($outer->getLine(), $frames[0]->getLine());
}
/**
* @covers Whoops\Exception\Inspector::getExceptionName
*/
public function testReturnsCorrectExceptionName()
{
$exception = $this->getException();
$inspector = $this->getInspectorInstance($exception);
$this->assertEquals(get_class($exception), $inspector->getExceptionName());
}
/**
* @covers Whoops\Exception\Inspector::__construct
* @covers Whoops\Exception\Inspector::getException
*/
public function testExceptionIsStoredAndReturned()
{
$exception = $this->getException();
$inspector = $this->getInspectorInstance($exception);
$this->assertSame($exception, $inspector->getException());
}
/**
* @covers Whoops\Exception\Inspector::getFrames
*/
public function testGetFramesReturnsCollection()
{
$exception = $this->getException();
$inspector = $this->getInspectorInstance($exception);
$this->assertInstanceOf('Whoops\\Exception\\FrameCollection', $inspector->getFrames());
}
/**
* @covers Whoops\Exception\Inspector::getFrames
*/
public function testGetFramesWithFiltersReturnsCollection()
{
$exception = $this->getException();
$inspector = $this->getInspectorInstance($exception);
$frames = $inspector->getFrames([
function(Frame $frame) {
return true;
},
]);
$this->assertInstanceOf('Whoops\\Exception\\FrameCollection', $frames);
$this->assertNotEmpty($frames);
}
/**
* @covers Whoops\Exception\Inspector::getFrames
*/
public function testGetFramesWithFiltersReturnsEmptyCollection()
{
$exception = $this->getException();
$inspector = $this->getInspectorInstance($exception);
$frames = $inspector->getFrames([
function(Frame $frame) {
return false;
},
]);
$this->assertInstanceOf('Whoops\\Exception\\FrameCollection', $frames);
$this->assertEmpty($frames);
}
/**
* @covers Whoops\Exception\Inspector::hasPreviousException
* @covers Whoops\Exception\Inspector::getPreviousExceptionInspector
*/
public function testPreviousException()
{
$previousException = $this->getException("I'm here first!");
$exception = $this->getException("Oh boy", 0, $previousException);
$inspector = $this->getInspectorInstance($exception);
$this->assertTrue($inspector->hasPreviousException());
$this->assertEquals($previousException, $inspector->getPreviousExceptionInspector()->getException());
}
/**
* @covers Whoops\Exception\Inspector::hasPreviousException
*/
public function testNegativeHasPreviousException()
{
$exception = $this->getException("Oh boy");
$inspector = $this->getInspectorInstance($exception);
$this->assertFalse($inspector->hasPreviousException());
}
/**
* @covers Whoops\Exception\Inspector::getPreviousExceptions
*/
public function testGetPreviousExceptionsReturnsListOfExceptions()
{
$exception1 = $this->getException('My first exception');
$exception2 = $this->getException('My second exception', 0, $exception1);
$exception3 = $this->getException('And the third one', 0, $exception2);
$inspector = $this->getInspectorInstance($exception3);
$previousExceptions = $inspector->getPreviousExceptions();
$this->assertCount(2, $previousExceptions);
$this->assertEquals($exception2, $previousExceptions[0]);
$this->assertEquals($exception1, $previousExceptions[1]);
}
/**
* @covers Whoops\Exception\Inspector::getPreviousExceptions
*/
public function testGetPreviousExceptionsReturnsEmptyListIfThereAreNoPreviousExceptions()
{
$exception = $this->getException('My exception');
$inspector = $this->getInspectorInstance($exception);
$previousExceptions = $inspector->getPreviousExceptions();
$this->assertCount(0, $previousExceptions);
}
/**
* @covers Whoops\Exception\Inspector::getPreviousExceptionMessages
*/
public function testGetPreviousExceptionMessages()
{
$exception1 = $this->getException('My first exception');
$exception2 = $this->getException('My second exception', 0, $exception1);
$exception3 = $this->getException('And the third one', 0, $exception2);
$inspector = $this->getInspectorInstance($exception3);
$previousExceptions = $inspector->getPreviousExceptionMessages();
$this->assertEquals($exception2->getMessage(), $previousExceptions[0]);
$this->assertEquals($exception1->getMessage(), $previousExceptions[1]);
}
/**
* @covers Whoops\Exception\Inspector::getPreviousExceptionCodes
*/
public function testGetPreviousExceptionCodes()
{
$exception1 = $this->getException('My first exception', 99);
$exception2 = $this->getException('My second exception', 20, $exception1);
$exception3 = $this->getException('And the third one', 10, $exception2);
$inspector = $this->getInspectorInstance($exception3);
$previousExceptions = $inspector->getPreviousExceptionCodes();
$this->assertEquals($exception2->getCode(), $previousExceptions[0]);
$this->assertEquals($exception1->getCode(), $previousExceptions[1]);
}
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/examples/example.php | examples/example.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*
* Run this example file with the PHP 5.4 web server with:
*
* $ cd project_dir
* $ php -S localhost:8080
*
* and access localhost:8080/examples/example.php through your browser
*
* Or just run it through apache/nginx/what-have-yous as usual.
*/
namespace Whoops\Example;
use Exception as BaseException;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/lib.php';
class Exception extends BaseException
{
}
$run = new Run();
$handler = new PrettyPageHandler();
// Add a custom table to the layout:
$handler->addDataTable('Ice-cream I like', [
'Chocolate' => 'yes',
'Coffee & chocolate' => 'a lot',
'Strawberry & chocolate' => 'it\'s alright',
'Vanilla' => 'ew',
]);
$handler->setApplicationPaths([__FILE__]);
$handler->addDataTableCallback('Details', function(\Whoops\Exception\Inspector $inspector) {
$data = array();
$exception = $inspector->getException();
if ($exception instanceof SomeSpecificException) {
$data['Important exception data'] = $exception->getSomeSpecificData();
}
$data['Exception class'] = get_class($exception);
$data['Exception code'] = $exception->getCode();
return $data;
});
$run->pushHandler($handler);
// Example: tag all frames inside a function with their function name
$run->pushHandler(function ($exception, $inspector, $run) {
$inspector->getFrames()->map(function ($frame) {
if ($function = $frame->getFunction()) {
$frame->addComment("This frame is within function '$function'", 'cpt-obvious');
}
return $frame;
});
});
$run->register();
function fooBar()
{
throw new Exception("Something broke!");
}
function bar()
{
whoops_add_stack_frame(function(){
fooBar();
});
}
bar();
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/examples/lib.php | examples/lib.php | <?php
function whoops_add_stack_frame($callback){
$callback();
}
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
filp/whoops | https://github.com/filp/whoops/blob/67342bc807854844244f219fb74687fdf2f62e00/examples/example-ajax-only.php | examples/example-ajax-only.php | <?php
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*
* Run this example file with the PHP 5.4 web server with:
*
* $ cd project_dir
* $ php -S localhost:8080
*
* and access localhost:8080/examples/example-ajax-only.php through your browser
*
* Or just run it through apache/nginx/what-have-yous as usual.
*/
namespace Whoops\Example;
use RuntimeException;
use Whoops\Handler\JsonResponseHandler;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;
require __DIR__ . '/../vendor/autoload.php';
$run = new Run();
// We want the error page to be shown by default, if this is a
// regular request, so that's the first thing to go into the stack:
$run->pushHandler(new PrettyPageHandler());
// Now, we want a second handler that will run before the error page,
// and immediately return an error message in JSON format, if something
// goes awry.
if (\Whoops\Util\Misc::isAjaxRequest()) {
$jsonHandler = new JsonResponseHandler();
// You can also tell JsonResponseHandler to give you a full stack trace:
// $jsonHandler->addTraceToOutput(true);
// You can also return a result compliant to the json:api spec
// re: http://jsonapi.org/examples/#error-objects
// tl;dr: error[] becomes errors[[]]
$jsonHandler->setJsonApi(true);
// And push it into the stack:
$run->pushHandler($jsonHandler);
}
// That's it! Register Whoops and throw a dummy exception:
$run->register();
throw new RuntimeException("Oh fudge napkins!");
| php | MIT | 67342bc807854844244f219fb74687fdf2f62e00 | 2026-01-04T15:02:56.580125Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Reader.php | src/Reader.php | <?php
namespace Maatwebsite\Excel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Collection;
use InvalidArgumentException;
use Maatwebsite\Excel\Concerns\HasReferencesToOtherSheets;
use Maatwebsite\Excel\Concerns\SkipsUnknownSheets;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithFormatData;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Events\AfterImport;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Events\ImportFailed;
use Maatwebsite\Excel\Exceptions\NoTypeDetectedException;
use Maatwebsite\Excel\Exceptions\SheetNotFoundException;
use Maatwebsite\Excel\Factories\ReaderFactory;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Files\TemporaryFileFactory;
use Maatwebsite\Excel\Transactions\TransactionHandler;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Reader\Exception;
use PhpOffice\PhpSpreadsheet\Reader\IReader;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Throwable;
/** @mixin Spreadsheet */
class Reader
{
use DelegatedMacroable, HasEventBus;
/**
* @var Spreadsheet
*/
protected $spreadsheet;
/**
* @var object[]
*/
protected $sheetImports = [];
/**
* @var TemporaryFile
*/
protected $currentFile;
/**
* @var TemporaryFileFactory
*/
protected $temporaryFileFactory;
/**
* @var TransactionHandler
*/
protected $transaction;
/**
* @var IReader
*/
protected $reader;
/**
* @param TemporaryFileFactory $temporaryFileFactory
* @param TransactionHandler $transaction
*/
public function __construct(TemporaryFileFactory $temporaryFileFactory, TransactionHandler $transaction)
{
$this->setDefaultValueBinder();
$this->transaction = $transaction;
$this->temporaryFileFactory = $temporaryFileFactory;
}
public function __sleep()
{
return ['spreadsheet', 'sheetImports', 'currentFile', 'temporaryFileFactory', 'reader'];
}
public function __wakeup()
{
$this->transaction = app(TransactionHandler::class);
}
/**
* @param object $import
* @param string|UploadedFile $filePath
* @param string|null $readerType
* @param string|null $disk
* @return \Illuminate\Foundation\Bus\PendingDispatch|$this
*
* @throws NoTypeDetectedException
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
* @throws Exception
*/
public function read($import, $filePath, ?string $readerType = null, ?string $disk = null)
{
$this->reader = $this->getReader($import, $filePath, $readerType, $disk);
if ($import instanceof WithChunkReading) {
return app(ChunkReader::class)->read($import, $this, $this->currentFile);
}
try {
$this->loadSpreadsheet($import);
($this->transaction)(function () use ($import) {
$sheetsToDisconnect = [];
foreach ($this->sheetImports as $index => $sheetImport) {
if ($sheet = $this->getSheet($import, $sheetImport, $index)) {
$sheet->import($sheetImport, $sheet->getStartRow($sheetImport));
// when using WithCalculatedFormulas we need to keep the sheet until all sheets are imported
if (!($sheetImport instanceof HasReferencesToOtherSheets)) {
$sheet->disconnect();
} else {
$sheetsToDisconnect[] = $sheet;
}
}
}
foreach ($sheetsToDisconnect as $sheet) {
$sheet->disconnect();
}
});
$this->afterImport($import);
} catch (Throwable $e) {
$this->raise(new ImportFailed($e));
$this->garbageCollect();
throw $e;
}
return $this;
}
/**
* @param object $import
* @param string|UploadedFile $filePath
* @param string $readerType
* @param string|null $disk
* @return array
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws NoTypeDetectedException
* @throws Exceptions\SheetNotFoundException
*/
public function toArray($import, $filePath, ?string $readerType = null, ?string $disk = null): array
{
$this->reader = $this->getReader($import, $filePath, $readerType, $disk);
$this->loadSpreadsheet($import);
$sheets = [];
$sheetsToDisconnect = [];
foreach ($this->sheetImports as $index => $sheetImport) {
$calculatesFormulas = $sheetImport instanceof WithCalculatedFormulas;
$formatData = $sheetImport instanceof WithFormatData;
if ($sheet = $this->getSheet($import, $sheetImport, $index)) {
$sheets[$index] = $sheet->toArray($sheetImport, $sheet->getStartRow($sheetImport), null, $calculatesFormulas, $formatData);
// when using WithCalculatedFormulas we need to keep the sheet until all sheets are imported
if (!($sheetImport instanceof HasReferencesToOtherSheets)) {
$sheet->disconnect();
} else {
$sheetsToDisconnect[] = $sheet;
}
}
}
foreach ($sheetsToDisconnect as $sheet) {
$sheet->disconnect();
}
$this->afterImport($import);
return $sheets;
}
/**
* @param object $import
* @param string|UploadedFile $filePath
* @param string $readerType
* @param string|null $disk
* @return Collection
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws NoTypeDetectedException
* @throws Exceptions\SheetNotFoundException
*/
public function toCollection($import, $filePath, ?string $readerType = null, ?string $disk = null): Collection
{
$this->reader = $this->getReader($import, $filePath, $readerType, $disk);
$this->loadSpreadsheet($import);
$sheets = new Collection();
$sheetsToDisconnect = [];
foreach ($this->sheetImports as $index => $sheetImport) {
$calculatesFormulas = $sheetImport instanceof WithCalculatedFormulas;
$formatData = $sheetImport instanceof WithFormatData;
if ($sheet = $this->getSheet($import, $sheetImport, $index)) {
$sheets->put($index, $sheet->toCollection($sheetImport, $sheet->getStartRow($sheetImport), null, $calculatesFormulas, $formatData));
// when using WithCalculatedFormulas we need to keep the sheet until all sheets are imported
if (!($sheetImport instanceof HasReferencesToOtherSheets)) {
$sheet->disconnect();
} else {
$sheetsToDisconnect[] = $sheet;
}
}
}
foreach ($sheetsToDisconnect as $sheet) {
$sheet->disconnect();
}
$this->afterImport($import);
return $sheets;
}
/**
* @return Spreadsheet
*/
public function getDelegate()
{
return $this->spreadsheet;
}
/**
* @return $this
*/
public function setDefaultValueBinder(): self
{
Cell::setValueBinder(
app(config('excel.value_binder.default', DefaultValueBinder::class))
);
return $this;
}
/**
* @param object $import
*/
public function loadSpreadsheet($import)
{
$this->sheetImports = $this->buildSheetImports($import);
$this->readSpreadsheet();
// When no multiple sheets, use the main import object
// for each loaded sheet in the spreadsheet
if (!$import instanceof WithMultipleSheets) {
$this->sheetImports = array_fill(0, $this->spreadsheet->getSheetCount(), $import);
}
$this->beforeImport($import);
}
public function readSpreadsheet()
{
$this->spreadsheet = $this->reader->load(
$this->currentFile->getLocalPath()
);
}
/**
* @param object $import
*/
public function beforeImport($import)
{
$this->raise(new BeforeImport($this, $import));
}
/**
* @param object $import
*/
public function afterImport($import)
{
$this->raise(new AfterImport($this, $import));
$this->garbageCollect();
}
/**
* @return IReader
*/
public function getPhpSpreadsheetReader(): IReader
{
return $this->reader;
}
/**
* @param object $import
* @return array
*/
public function getWorksheets($import): array
{
// Csv doesn't have worksheets.
if (!method_exists($this->reader, 'listWorksheetNames')) {
return ['Worksheet' => $import];
}
$worksheets = [];
$worksheetNames = $this->reader->listWorksheetNames($this->currentFile->getLocalPath());
if ($import instanceof WithMultipleSheets) {
$sheetImports = $import->sheets();
foreach ($sheetImports as $index => $sheetImport) {
// Translate index to name.
if (is_numeric($index)) {
$index = $worksheetNames[$index] ?? $index;
}
// Specify with worksheet name should have which import.
$worksheets[$index] = $sheetImport;
}
// Load specific sheets.
if (method_exists($this->reader, 'setLoadSheetsOnly')) {
$this->reader->setLoadSheetsOnly(
collect($worksheetNames)->intersect(array_keys($worksheets))->values()->all()
);
}
} else {
// Each worksheet the same import class.
foreach ($worksheetNames as $name) {
$worksheets[$name] = $import;
}
}
return $worksheets;
}
/**
* @return array
*/
public function getTotalRows(): array
{
$info = $this->reader->listWorksheetInfo($this->currentFile->getLocalPath());
$totalRows = [];
foreach ($info as $sheet) {
$totalRows[$sheet['worksheetName']] = $sheet['totalRows'];
}
return $totalRows;
}
/**
* @param $import
* @param $sheetImport
* @param $index
* @return Sheet|null
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws SheetNotFoundException
*/
protected function getSheet($import, $sheetImport, $index)
{
try {
return Sheet::make($this->spreadsheet, $index);
} catch (SheetNotFoundException $e) {
if ($import instanceof SkipsUnknownSheets) {
$import->onUnknownSheet($index);
return null;
}
if ($sheetImport instanceof SkipsUnknownSheets) {
$sheetImport->onUnknownSheet($index);
return null;
}
throw $e;
}
}
/**
* @param object $import
* @return array
*/
private function buildSheetImports($import): array
{
$sheetImports = [];
if ($import instanceof WithMultipleSheets) {
$sheetImports = $import->sheets();
// When only sheet names are given and the reader has
// an option to load only the selected sheets.
if (
method_exists($this->reader, 'setLoadSheetsOnly')
&& count(array_filter(array_keys($sheetImports), 'is_numeric')) === 0
) {
$this->reader->setLoadSheetsOnly(array_keys($sheetImports));
}
}
return $sheetImports;
}
/**
* @param object $import
* @param string|UploadedFile $filePath
* @param string|null $readerType
* @param string $disk
* @return IReader
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
* @throws NoTypeDetectedException
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
* @throws InvalidArgumentException
*/
private function getReader($import, $filePath, ?string $readerType = null, ?string $disk = null): IReader
{
$shouldQueue = $import instanceof ShouldQueue;
if ($shouldQueue && !$import instanceof WithChunkReading) {
throw new InvalidArgumentException('ShouldQueue is only supported in combination with WithChunkReading.');
}
if ($import instanceof WithEvents) {
$this->registerListeners($import->registerEvents());
}
if ($import instanceof WithCustomValueBinder) {
Cell::setValueBinder($import);
}
$fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
$temporaryFile = $shouldQueue ? $this->temporaryFileFactory->make($fileExtension) : $this->temporaryFileFactory->makeLocal(null, $fileExtension);
$this->currentFile = $temporaryFile->copyFrom(
$filePath,
$disk
);
return ReaderFactory::make(
$import,
$this->currentFile,
$readerType
);
}
/**
* Garbage collect.
*/
private function garbageCollect()
{
$this->clearListeners();
$this->setDefaultValueBinder();
// Force garbage collecting
unset($this->sheetImports, $this->spreadsheet);
$this->currentFile->delete();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/ChunkReader.php | src/ChunkReader.php | <?php
namespace Maatwebsite\Excel;
use Illuminate\Bus\Queueable;
use Illuminate\Container\Container;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\PendingDispatch;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Jobs\SyncJob;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ShouldQueueWithoutChain;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithLimit;
use Maatwebsite\Excel\Concerns\WithProgressBar;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Imports\HeadingRowExtractor;
use Maatwebsite\Excel\Jobs\AfterImportJob;
use Maatwebsite\Excel\Jobs\QueueImport;
use Maatwebsite\Excel\Jobs\ReadChunk;
use Throwable;
class ChunkReader
{
/**
* @var Container
*/
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* @param WithChunkReading $import
* @param Reader $reader
* @param TemporaryFile $temporaryFile
* @return PendingDispatch|Collection|null
*/
public function read(WithChunkReading $import, Reader $reader, TemporaryFile $temporaryFile)
{
if ($import instanceof WithEvents) {
$reader->beforeImport($import);
}
$chunkSize = $import->chunkSize();
$totalRows = $reader->getTotalRows();
$worksheets = $reader->getWorksheets($import);
$queue = property_exists($import, 'queue') ? $import->queue : null;
$delayCleanup = property_exists($import, 'cleanupInterval') ? $import->cleanupInterval : 60;
if ($import instanceof WithProgressBar) {
$import->getConsoleOutput()->progressStart(array_sum($totalRows));
}
$jobs = new Collection();
foreach ($worksheets as $name => $sheetImport) {
$startRow = HeadingRowExtractor::determineStartRow($sheetImport);
if ($sheetImport instanceof WithLimit) {
$limit = $sheetImport->limit();
if ($limit <= $totalRows[$name]) {
$totalRows[$name] = $sheetImport->limit();
}
}
for ($currentRow = $startRow; $currentRow <= $totalRows[$name]; $currentRow += $chunkSize) {
$jobs->push(new ReadChunk(
$import,
$reader->getPhpSpreadsheetReader(),
$temporaryFile,
$name,
$sheetImport,
$currentRow,
$chunkSize
));
}
}
$afterImportJob = new AfterImportJob($import, $reader);
if ($import instanceof ShouldQueueWithoutChain) {
$afterImportJob->setInterval($delayCleanup);
$afterImportJob->setDependencies($jobs);
$jobs->push($afterImportJob->delay($delayCleanup));
return $jobs->each(function ($job) use ($queue) {
dispatch($job->onQueue($queue));
});
}
$jobs->push($afterImportJob);
if ($import instanceof ShouldQueue) {
return new PendingDispatch(
(new QueueImport($import))->chain($jobs->toArray())
);
}
$jobs->each(function ($job) {
try {
function_exists('dispatch_now')
? dispatch_now($job)
: $this->dispatchNow($job);
} catch (Throwable $e) {
if (method_exists($job, 'failed')) {
$job->failed($e);
}
throw $e;
}
});
if ($import instanceof WithProgressBar) {
$import->getConsoleOutput()->progressFinish();
}
unset($jobs);
return null;
}
/**
* Dispatch a command to its appropriate handler in the current process without using the synchronous queue.
*
* @param object $command
* @param mixed $handler
* @return mixed
*/
protected function dispatchNow($command, $handler = null)
{
$uses = class_uses_recursive($command);
if (in_array(InteractsWithQueue::class, $uses) &&
in_array(Queueable::class, $uses) && !$command->job
) {
$command->setJob(new SyncJob($this->container, json_encode([]), 'sync', 'sync'));
}
$method = method_exists($command, 'handle') ? 'handle' : '__invoke';
return $this->container->call([$command, $method]);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Writer.php | src/Writer.php | <?php
namespace Maatwebsite\Excel;
use Maatwebsite\Excel\Concerns\WithBackgroundColor;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithDefaultStyles;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithProperties;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Events\BeforeWriting;
use Maatwebsite\Excel\Factories\WriterFactory;
use Maatwebsite\Excel\Files\RemoteTemporaryFile;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Files\TemporaryFileFactory;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
/** @mixin Spreadsheet */
class Writer
{
use DelegatedMacroable, HasEventBus;
/**
* @var Spreadsheet
*/
protected $spreadsheet;
/**
* @var object
*/
protected $exportable;
/**
* @var TemporaryFileFactory
*/
protected $temporaryFileFactory;
/**
* @param TemporaryFileFactory $temporaryFileFactory
*/
public function __construct(TemporaryFileFactory $temporaryFileFactory)
{
$this->temporaryFileFactory = $temporaryFileFactory;
$this->setDefaultValueBinder();
}
/**
* @param object $export
* @param string $writerType
* @return TemporaryFile
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public function export($export, string $writerType): TemporaryFile
{
$this->open($export);
$sheetExports = [$export];
if ($export instanceof WithMultipleSheets) {
$sheetExports = $export->sheets();
}
foreach ($sheetExports as $sheetExport) {
$this->addNewSheet()->export($sheetExport);
}
return $this->write($export, $this->temporaryFileFactory->makeLocal(null, strtolower($writerType)), $writerType);
}
/**
* @param object $export
* @return $this
*/
public function open($export)
{
$this->exportable = $export;
if ($export instanceof WithEvents) {
$this->registerListeners($export->registerEvents());
}
$this->exportable = $export;
$this->spreadsheet = new Spreadsheet;
$this->spreadsheet->disconnectWorksheets();
if ($export instanceof WithCustomValueBinder) {
Cell::setValueBinder($export);
}
$this->handleDocumentProperties($export);
if ($export instanceof WithBackgroundColor) {
$defaultStyle = $this->spreadsheet->getDefaultStyle();
$backgroundColor = $export->backgroundColor();
if (is_string($backgroundColor)) {
$defaultStyle->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($backgroundColor);
}
if (is_array($backgroundColor)) {
$defaultStyle->applyFromArray(['fill' => $backgroundColor]);
}
if ($backgroundColor instanceof Color) {
$defaultStyle->getFill()->setFillType(Fill::FILL_SOLID)->setStartColor($backgroundColor);
}
}
if ($export instanceof WithDefaultStyles) {
$defaultStyle = $this->spreadsheet->getDefaultStyle();
$styles = $export->defaultStyles($defaultStyle);
if (is_array($styles)) {
$defaultStyle->applyFromArray($styles);
}
}
$this->raise(new BeforeExport($this, $this->exportable));
return $this;
}
/**
* @param TemporaryFile $tempFile
* @param string $writerType
* @return Writer
*
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
public function reopen(TemporaryFile $tempFile, string $writerType)
{
$reader = IOFactory::createReader($writerType);
$this->spreadsheet = $reader->load($tempFile->sync()->getLocalPath());
return $this;
}
/**
* Determine if the application is running in a serverless environment.
*
* @return bool
*/
public function isRunningServerless(): bool
{
return isset($_ENV['AWS_LAMBDA_RUNTIME_API']);
}
/**
* @param object $export
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @return TemporaryFile
*
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public function write($export, TemporaryFile $temporaryFile, string $writerType): TemporaryFile
{
$this->exportable = $export;
$this->spreadsheet->setActiveSheetIndex(0);
$this->raise(new BeforeWriting($this, $this->exportable));
$writer = WriterFactory::make(
$writerType,
$this->spreadsheet,
$export
);
if ($temporaryFile instanceof RemoteTemporaryFile && !$temporaryFile->existsLocally() && !$this->isRunningServerless()) {
// just ensure that local copy exists (it creates the directory structure),
// no need to copy remote content since it will be overwritten below
$temporaryFile->sync(false);
}
$writer->save(
$temporaryFile->getLocalPath()
);
if ($temporaryFile instanceof RemoteTemporaryFile) {
$temporaryFile->updateRemote();
$temporaryFile->deleteLocalCopy();
}
$this->clearListeners();
$this->spreadsheet->disconnectWorksheets();
unset($this->spreadsheet);
return $temporaryFile;
}
/**
* @param int|null $sheetIndex
* @return Sheet
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public function addNewSheet(?int $sheetIndex = null)
{
return new Sheet($this->spreadsheet->createSheet($sheetIndex));
}
/**
* @return Spreadsheet
*/
public function getDelegate()
{
return $this->spreadsheet;
}
/**
* @return $this
*/
public function setDefaultValueBinder()
{
Cell::setValueBinder(
app(config('excel.value_binder.default', DefaultValueBinder::class))
);
return $this;
}
/**
* @param int $sheetIndex
* @return Sheet
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public function getSheetByIndex(int $sheetIndex)
{
return new Sheet($this->getDelegate()->getSheet($sheetIndex));
}
/**
* @param string $concern
* @return bool
*/
public function hasConcern($concern): bool
{
return $this->exportable instanceof $concern;
}
/**
* @param object $export
*/
protected function handleDocumentProperties($export)
{
$properties = config('excel.exports.properties', []);
if ($export instanceof WithProperties) {
$properties = array_merge($properties, $export->properties());
}
if ($export instanceof WithTitle) {
$properties = array_merge($properties, ['title' => $export->title()]);
}
$props = $this->spreadsheet->getProperties();
foreach (array_filter($properties) as $property => $value) {
switch ($property) {
case 'title':
$props->setTitle($value);
break;
case 'description':
$props->setDescription($value);
break;
case 'creator':
$props->setCreator($value);
break;
case 'lastModifiedBy':
$props->setLastModifiedBy($value);
break;
case 'subject':
$props->setSubject($value);
break;
case 'keywords':
$props->setKeywords($value);
break;
case 'category':
$props->setCategory($value);
break;
case 'manager':
$props->setManager($value);
break;
case 'company':
$props->setCompany($value);
break;
}
}
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/MappedReader.php | src/MappedReader.php | <?php
namespace Maatwebsite\Excel;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
use Maatwebsite\Excel\Concerns\WithFormatData;
use Maatwebsite\Excel\Concerns\WithMappedCells;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class MappedReader
{
/**
* @param WithMappedCells $import
* @param Worksheet $worksheet
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public function map(WithMappedCells $import, Worksheet $worksheet)
{
$mapped = $import->mapping();
array_walk_recursive($mapped, function (&$coordinate) use ($import, $worksheet) {
$cell = Cell::make($worksheet, $coordinate);
$coordinate = $cell->getValue(
null,
$import instanceof WithCalculatedFormulas,
$import instanceof WithFormatData
);
});
if ($import instanceof ToModel) {
$model = $import->model($mapped);
if ($model) {
$model->saveOrFail();
}
}
if ($import instanceof ToCollection) {
$import->collection(new Collection($mapped));
}
if ($import instanceof ToArray) {
$import->array($mapped);
}
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Cell.php | src/Cell.php | <?php
namespace Maatwebsite\Excel;
use Illuminate\Pipeline\Pipeline;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use PhpOffice\PhpSpreadsheet\Cell\Cell as SpreadsheetCell;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
/** @mixin SpreadsheetCell */
class Cell
{
use DelegatedMacroable;
/**
* @var SpreadsheetCell
*/
private $cell;
/**
* @param SpreadsheetCell $cell
*/
public function __construct(SpreadsheetCell $cell)
{
$this->cell = $cell;
}
/**
* @param Worksheet $worksheet
* @param string $coordinate
* @return Cell
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public static function make(Worksheet $worksheet, string $coordinate)
{
return new static($worksheet->getCell($coordinate));
}
/**
* @return SpreadsheetCell
*/
public function getDelegate(): SpreadsheetCell
{
return $this->cell;
}
/**
* @param null $nullValue
* @param bool $calculateFormulas
* @param bool $formatData
* @return mixed
*/
public function getValue($nullValue = null, $calculateFormulas = false, $formatData = true)
{
$value = $nullValue;
if ($this->cell->getValue() !== null) {
if ($this->cell->getValue() instanceof RichText) {
$value = $this->cell->getValue()->getPlainText();
} elseif ($calculateFormulas) {
try {
$value = $this->cell->getCalculatedValue();
} catch (Exception $e) {
$value = $this->cell->getOldCalculatedValue();
}
} else {
$value = $this->cell->getValue();
}
if ($formatData) {
$style = $this->cell->getWorksheet()->getParent()->getCellXfByIndex($this->cell->getXfIndex());
$value = NumberFormat::toFormattedString(
$value,
($style && $style->getNumberFormat()) ? $style->getNumberFormat()->getFormatCode() : NumberFormat::FORMAT_GENERAL
);
}
}
return app(Pipeline::class)->send($value)->through(config('excel.imports.cells.middleware', []))->thenReturn();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/QueuedWriter.php | src/QueuedWriter.php | <?php
namespace Maatwebsite\Excel;
use Illuminate\Foundation\Bus\PendingDispatch;
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\WithCustomChunkSize;
use Maatwebsite\Excel\Concerns\WithCustomQuerySize;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Files\TemporaryFileFactory;
use Maatwebsite\Excel\Jobs\AppendDataToSheet;
use Maatwebsite\Excel\Jobs\AppendPaginatedToSheet;
use Maatwebsite\Excel\Jobs\AppendQueryToSheet;
use Maatwebsite\Excel\Jobs\AppendViewToSheet;
use Maatwebsite\Excel\Jobs\CloseSheet;
use Maatwebsite\Excel\Jobs\QueueExport;
use Maatwebsite\Excel\Jobs\StoreQueuedExport;
use Traversable;
class QueuedWriter
{
/**
* @var Writer
*/
protected $writer;
/**
* @var int
*/
protected $chunkSize;
/**
* @var TemporaryFileFactory
*/
protected $temporaryFileFactory;
/**
* @param Writer $writer
* @param TemporaryFileFactory $temporaryFileFactory
*/
public function __construct(Writer $writer, TemporaryFileFactory $temporaryFileFactory)
{
$this->writer = $writer;
$this->chunkSize = config('excel.exports.chunk_size', 1000);
$this->temporaryFileFactory = $temporaryFileFactory;
}
/**
* @param object $export
* @param string $filePath
* @param string $disk
* @param string|null $writerType
* @param array|string $diskOptions
* @return \Illuminate\Foundation\Bus\PendingDispatch
*/
public function store($export, string $filePath, ?string $disk = null, ?string $writerType = null, $diskOptions = [])
{
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
$temporaryFile = $this->temporaryFileFactory->make($extension);
$jobs = $this->buildExportJobs($export, $temporaryFile, $writerType);
$jobs->push(new StoreQueuedExport(
$temporaryFile,
$filePath,
$disk,
$diskOptions
));
return new PendingDispatch(
(new QueueExport($export, $temporaryFile, $writerType))->chain($jobs->toArray())
);
}
/**
* @param object $export
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @return Collection
*/
private function buildExportJobs($export, TemporaryFile $temporaryFile, string $writerType): Collection
{
$sheetExports = [$export];
if ($export instanceof WithMultipleSheets) {
$sheetExports = $export->sheets();
}
$jobs = new Collection;
foreach ($sheetExports as $sheetIndex => $sheetExport) {
if ($sheetExport instanceof FromCollection) {
$jobs = $jobs->merge($this->exportCollection($sheetExport, $temporaryFile, $writerType, $sheetIndex));
} elseif ($sheetExport instanceof FromQuery) {
$jobs = $jobs->merge($this->exportQuery($sheetExport, $temporaryFile, $writerType, $sheetIndex));
} elseif ($sheetExport instanceof FromView) {
$jobs = $jobs->merge($this->exportView($sheetExport, $temporaryFile, $writerType, $sheetIndex));
}
$jobs->push(new CloseSheet($sheetExport, $temporaryFile, $writerType, $sheetIndex));
}
return $jobs;
}
/**
* @param FromCollection $export
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @param int $sheetIndex
* @return Collection|LazyCollection
*/
private function exportCollection(
FromCollection $export,
TemporaryFile $temporaryFile,
string $writerType,
int $sheetIndex
) {
return $export
->collection()
->chunk($this->getChunkSize($export))
->map(function ($rows) use ($writerType, $temporaryFile, $sheetIndex, $export) {
if ($rows instanceof Traversable) {
$rows = iterator_to_array($rows);
}
return new AppendDataToSheet(
$export,
$temporaryFile,
$writerType,
$sheetIndex,
$rows
);
});
}
/**
* @param FromQuery $export
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @param int $sheetIndex
* @return Collection
*/
private function exportQuery(
FromQuery $export,
TemporaryFile $temporaryFile,
string $writerType,
int $sheetIndex
): Collection {
$query = $export->query();
if ($query instanceof \Laravel\Scout\Builder) {
return $this->exportScout($export, $temporaryFile, $writerType, $sheetIndex);
}
$count = $export instanceof WithCustomQuerySize ? $export->querySize() : $query->count();
$spins = ceil($count / $this->getChunkSize($export));
$jobs = new Collection();
for ($page = 1; $page <= $spins; $page++) {
$jobs->push(new AppendQueryToSheet(
$export,
$temporaryFile,
$writerType,
$sheetIndex,
$page,
$this->getChunkSize($export)
));
}
return $jobs;
}
/**
* @param FromQuery $export
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @param int $sheetIndex
* @return Collection
*/
private function exportScout(
FromQuery $export,
TemporaryFile $temporaryFile,
string $writerType,
int $sheetIndex
): Collection {
$jobs = new Collection();
$chunk = $export->query()->paginate($this->getChunkSize($export));
// Append first page
$jobs->push(new AppendDataToSheet(
$export,
$temporaryFile,
$writerType,
$sheetIndex,
$chunk->items()
));
// Append rest of pages
for ($page = 2; $page <= $chunk->lastPage(); $page++) {
$jobs->push(new AppendPaginatedToSheet(
$export,
$temporaryFile,
$writerType,
$sheetIndex,
$page,
$this->getChunkSize($export)
));
}
return $jobs;
}
/**
* @param FromView $export
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @param int $sheetIndex
* @return Collection
*/
private function exportView(
FromView $export,
TemporaryFile $temporaryFile,
string $writerType,
int $sheetIndex
): Collection {
$jobs = new Collection();
$jobs->push(new AppendViewToSheet(
$export,
$temporaryFile,
$writerType,
$sheetIndex
));
return $jobs;
}
/**
* @param object|WithCustomChunkSize $export
* @return int
*/
private function getChunkSize($export): int
{
if ($export instanceof WithCustomChunkSize) {
return $export->chunkSize();
}
return $this->chunkSize;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Exporter.php | src/Exporter.php | <?php
namespace Maatwebsite\Excel;
interface Exporter
{
/**
* @param object $export
* @param string|null $fileName
* @param string $writerType
* @param array $headers
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
public function download($export, string $fileName, ?string $writerType = null, array $headers = []);
/**
* @param object $export
* @param string $filePath
* @param string|null $diskName
* @param string $writerType
* @param mixed $diskOptions
* @return bool
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
public function store($export, string $filePath, ?string $disk = null, ?string $writerType = null, $diskOptions = []);
/**
* @param object $export
* @param string $filePath
* @param string|null $disk
* @param string $writerType
* @param mixed $diskOptions
* @return \Illuminate\Foundation\Bus\PendingDispatch
*/
public function queue($export, string $filePath, ?string $disk = null, ?string $writerType = null, $diskOptions = []);
/**
* @param object $export
* @param string $writerType
* @return string
*/
public function raw($export, string $writerType);
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/HasEventBus.php | src/HasEventBus.php | <?php
namespace Maatwebsite\Excel;
trait HasEventBus
{
/**
* @var array
*/
protected static $globalEvents = [];
/**
* @var array
*/
protected $events = [];
/**
* Register local event listeners.
*
* @param array $listeners
*/
public function registerListeners(array $listeners)
{
foreach ($listeners as $event => $listener) {
$this->events[$event][] = $listener;
}
}
public function clearListeners()
{
$this->events = [];
}
/**
* Register a global event listener.
*
* @param string $event
* @param callable $listener
*/
public static function listen(string $event, callable $listener)
{
static::$globalEvents[$event][] = $listener;
}
/**
* @param object $event
*/
public function raise($event)
{
foreach ($this->listeners($event) as $listener) {
$listener($event);
}
}
/**
* @param object $event
* @return callable[]
*/
public function listeners($event): array
{
$name = \get_class($event);
$localListeners = $this->events[$name] ?? [];
$globalListeners = static::$globalEvents[$name] ?? [];
return array_merge($globalListeners, $localListeners);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/SettingsProvider.php | src/SettingsProvider.php | <?php
namespace Maatwebsite\Excel;
use Maatwebsite\Excel\Cache\CacheManager;
use PhpOffice\PhpSpreadsheet\Settings;
class SettingsProvider
{
/**
* @var CacheManager
*/
private $cache;
public function __construct(CacheManager $cache)
{
$this->cache = $cache;
}
/**
* Provide PhpSpreadsheet settings.
*/
public function provide()
{
$this->configureCellCaching();
}
protected function configureCellCaching()
{
Settings::setCache(
$this->cache->driver()
);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Row.php | src/Row.php | <?php
namespace Maatwebsite\Excel;
use ArrayAccess;
use Closure;
use Illuminate\Support\Collection;
use PhpOffice\PhpSpreadsheet\Worksheet\Row as SpreadsheetRow;
/** @mixin SpreadsheetRow */
class Row implements ArrayAccess
{
use DelegatedMacroable;
/**
* @var array
*/
protected $headingRow = [];
/**
* @var array
*/
protected $headerIsGrouped = [];
/**
* @var \Closure
*/
protected $preparationCallback;
/**
* @var SpreadsheetRow
*/
protected $row;
/**
* @var array|null
*/
protected $rowCache;
/**
* @var bool|null
*/
protected $rowCacheFormatData;
/**
* @var string|null
*/
protected $rowCacheEndColumn;
/**
* @param SpreadsheetRow $row
* @param array $headingRow
* @param array $headerIsGrouped
*/
public function __construct(SpreadsheetRow $row, array $headingRow = [], array $headerIsGrouped = [])
{
$this->row = $row;
$this->headingRow = $headingRow;
$this->headerIsGrouped = $headerIsGrouped;
}
/**
* @return SpreadsheetRow
*/
public function getDelegate(): SpreadsheetRow
{
return $this->row;
}
/**
* @param null $nullValue
* @param bool $calculateFormulas
* @param bool $formatData
* @param string|null $endColumn
* @return Collection
*/
public function toCollection($nullValue = null, $calculateFormulas = false, $formatData = true, ?string $endColumn = null): Collection
{
return new Collection($this->toArray($nullValue, $calculateFormulas, $formatData, $endColumn));
}
/**
* @param null $nullValue
* @param bool $calculateFormulas
* @param bool $formatData
* @param string|null $endColumn
* @return array
*/
public function toArray($nullValue = null, $calculateFormulas = false, $formatData = true, ?string $endColumn = null)
{
if (is_array($this->rowCache) && ($this->rowCacheFormatData === $formatData) && ($this->rowCacheEndColumn === $endColumn)) {
return $this->rowCache;
}
$cells = [];
$i = 0;
foreach ($this->row->getCellIterator('A', $endColumn) as $cell) {
$value = (new Cell($cell))->getValue($nullValue, $calculateFormulas, $formatData);
if (isset($this->headingRow[$i])) {
if (!$this->headerIsGrouped[$i]) {
$cells[$this->headingRow[$i]] = $value;
} else {
$cells[$this->headingRow[$i]][] = $value;
}
} else {
$cells[] = $value;
}
$i++;
}
if (isset($this->preparationCallback)) {
$cells = ($this->preparationCallback)($cells, $this->row->getRowIndex());
}
$this->rowCache = $cells;
$this->rowCacheFormatData = $formatData;
$this->rowCacheEndColumn = $endColumn;
return $cells;
}
/**
* @param bool $calculateFormulas
* @param string|null $endColumn
* @return bool
*/
public function isEmpty($calculateFormulas = false, ?string $endColumn = null): bool
{
return count(array_filter($this->toArray(null, $calculateFormulas, false, $endColumn))) === 0;
}
/**
* @return int
*/
public function getIndex(): int
{
return $this->row->getRowIndex();
}
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return isset($this->toArray()[$offset]);
}
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->toArray()[$offset];
}
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
//
}
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
//
}
/**
* @param \Closure $preparationCallback
*
* @internal
*/
public function setPreparationCallback(?Closure $preparationCallback = null)
{
$this->preparationCallback = $preparationCallback;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Importer.php | src/Importer.php | <?php
namespace Maatwebsite\Excel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Collection;
interface Importer
{
/**
* @param object $import
* @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $filePath
* @param string|null $disk
* @param string|null $readerType
* @return Reader|\Illuminate\Foundation\Bus\PendingDispatch
*/
public function import($import, $filePath, ?string $disk = null, ?string $readerType = null);
/**
* @param object $import
* @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $filePath
* @param string|null $disk
* @param string|null $readerType
* @return array
*/
public function toArray($import, $filePath, ?string $disk = null, ?string $readerType = null): array;
/**
* @param object $import
* @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $filePath
* @param string|null $disk
* @param string|null $readerType
* @return Collection
*/
public function toCollection($import, $filePath, ?string $disk = null, ?string $readerType = null): Collection;
/**
* @param ShouldQueue $import
* @param string|\Symfony\Component\HttpFoundation\File\UploadedFile $filePath
* @param string|null $disk
* @param string $readerType
* @return \Illuminate\Foundation\Bus\PendingDispatch
*/
public function queueImport(ShouldQueue $import, $filePath, ?string $disk = null, ?string $readerType = null);
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/DelegatedMacroable.php | src/DelegatedMacroable.php | <?php
namespace Maatwebsite\Excel;
use Illuminate\Support\Traits\Macroable;
trait DelegatedMacroable
{
use Macroable {
__call as __callMacro;
}
/**
* Dynamically handle calls to the class.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if (method_exists($this->getDelegate(), $method)) {
return call_user_func_array([$this->getDelegate(), $method], $parameters);
}
array_unshift($parameters, $this);
return $this->__callMacro($method, $parameters);
}
/**
* @return object
*/
abstract public function getDelegate();
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Excel.php | src/Excel.php | <?php
namespace Maatwebsite\Excel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\PendingDispatch;
use Illuminate\Support\Collection;
use Illuminate\Support\Traits\Macroable;
use Maatwebsite\Excel\Files\Filesystem;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Helpers\FileTypeDetector;
class Excel implements Exporter, Importer
{
use Macroable, RegistersCustomConcerns;
const XLSX = 'Xlsx';
const CSV = 'Csv';
const TSV = 'Csv';
const ODS = 'Ods';
const XLS = 'Xls';
const SLK = 'Slk';
const XML = 'Xml';
const GNUMERIC = 'Gnumeric';
const HTML = 'Html';
const MPDF = 'Mpdf';
const DOMPDF = 'Dompdf';
const TCPDF = 'Tcpdf';
/**
* @var Writer
*/
protected $writer;
/**
* @var QueuedWriter
*/
protected $queuedWriter;
/**
* @var Filesystem
*/
protected $filesystem;
/**
* @var Reader
*/
private $reader;
/**
* @param Writer $writer
* @param QueuedWriter $queuedWriter
* @param Reader $reader
* @param Filesystem $filesystem
*/
public function __construct(
Writer $writer,
QueuedWriter $queuedWriter,
Reader $reader,
Filesystem $filesystem
) {
$this->writer = $writer;
$this->reader = $reader;
$this->filesystem = $filesystem;
$this->queuedWriter = $queuedWriter;
}
/**
* {@inheritdoc}
*/
public function download($export, string $fileName, ?string $writerType = null, array $headers = [])
{
// Clear output buffer to prevent stuff being prepended to the Excel output.
if (ob_get_length() > 0) {
ob_end_clean();
ob_start();
}
return response()->download(
$this->export($export, $fileName, $writerType)->getLocalPath(),
$fileName,
$headers
)->deleteFileAfterSend(true);
}
/**
* {@inheritdoc}
*
* @param string|null $disk Fallback for usage with named properties
*/
public function store($export, string $filePath, ?string $diskName = null, ?string $writerType = null, $diskOptions = [], ?string $disk = null)
{
if ($export instanceof ShouldQueue) {
return $this->queue($export, $filePath, $diskName ?: $disk, $writerType, $diskOptions);
}
$temporaryFile = $this->export($export, $filePath, $writerType);
$exported = $this->filesystem->disk($diskName ?: $disk, $diskOptions)->copy(
$temporaryFile,
$filePath
);
$temporaryFile->delete();
return $exported;
}
/**
* {@inheritdoc}
*/
public function queue($export, string $filePath, ?string $disk = null, ?string $writerType = null, $diskOptions = [])
{
$writerType = FileTypeDetector::detectStrict($filePath, $writerType);
return $this->queuedWriter->store(
$export,
$filePath,
$disk,
$writerType,
$diskOptions
);
}
/**
* {@inheritdoc}
*/
public function raw($export, string $writerType)
{
$temporaryFile = $this->writer->export($export, $writerType);
$contents = $temporaryFile->contents();
$temporaryFile->delete();
return $contents;
}
/**
* {@inheritdoc}
*/
public function import($import, $filePath, ?string $disk = null, ?string $readerType = null)
{
$readerType = FileTypeDetector::detect($filePath, $readerType);
$response = $this->reader->read($import, $filePath, $readerType, $disk);
if ($response instanceof PendingDispatch) {
return $response;
}
return $this;
}
/**
* {@inheritdoc}
*/
public function toArray($import, $filePath, ?string $disk = null, ?string $readerType = null): array
{
$readerType = FileTypeDetector::detect($filePath, $readerType);
return $this->reader->toArray($import, $filePath, $readerType, $disk);
}
/**
* {@inheritdoc}
*/
public function toCollection($import, $filePath, ?string $disk = null, ?string $readerType = null): Collection
{
$readerType = FileTypeDetector::detect($filePath, $readerType);
return $this->reader->toCollection($import, $filePath, $readerType, $disk);
}
/**
* {@inheritdoc}
*/
public function queueImport(ShouldQueue $import, $filePath, ?string $disk = null, ?string $readerType = null)
{
return $this->import($import, $filePath, $disk, $readerType);
}
/**
* @param object $export
* @param string|null $fileName
* @param string $writerType
* @return TemporaryFile
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
protected function export($export, string $fileName, ?string $writerType = null): TemporaryFile
{
$writerType = FileTypeDetector::detectStrict($fileName, $writerType);
return $this->writer->export($export, $writerType);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/ExcelServiceProvider.php | src/ExcelServiceProvider.php | <?php
namespace Maatwebsite\Excel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
use Laravel\Lumen\Application as LumenApplication;
use Maatwebsite\Excel\Cache\CacheManager;
use Maatwebsite\Excel\Console\ExportMakeCommand;
use Maatwebsite\Excel\Console\ImportMakeCommand;
use Maatwebsite\Excel\Files\Filesystem;
use Maatwebsite\Excel\Files\TemporaryFileFactory;
use Maatwebsite\Excel\Mixins\DownloadCollectionMixin;
use Maatwebsite\Excel\Mixins\DownloadQueryMacro;
use Maatwebsite\Excel\Mixins\ImportAsMacro;
use Maatwebsite\Excel\Mixins\ImportMacro;
use Maatwebsite\Excel\Mixins\StoreCollectionMixin;
use Maatwebsite\Excel\Mixins\StoreQueryMacro;
use Maatwebsite\Excel\Transactions\TransactionHandler;
use Maatwebsite\Excel\Transactions\TransactionManager;
class ExcelServiceProvider extends ServiceProvider
{
/**
* {@inheritdoc}
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/Console/stubs/export.model.stub' => base_path('stubs/export.model.stub'),
__DIR__ . '/Console/stubs/export.plain.stub' => base_path('stubs/export.plain.stub'),
__DIR__ . '/Console/stubs/export.query.stub' => base_path('stubs/export.query.stub'),
__DIR__ . '/Console/stubs/export.query-model.stub' => base_path('stubs/export.query-model.stub'),
__DIR__ . '/Console/stubs/import.collection.stub' => base_path('stubs/import.collection.stub'),
__DIR__ . '/Console/stubs/import.model.stub' => base_path('stubs/import.model.stub'),
], 'stubs');
if ($this->app instanceof LumenApplication) {
$this->app->configure('excel');
} else {
$this->publishes([
$this->getConfigFile() => config_path('excel.php'),
], 'config');
}
}
if ($this->app instanceof \Illuminate\Foundation\Application) {
// Laravel
$this->app->booted(function ($app) {
$app->make(SettingsProvider::class)->provide();
});
} else {
// Lumen
$this->app->make(SettingsProvider::class)->provide();
}
}
/**
* {@inheritdoc}
*/
public function register()
{
$this->mergeConfigFrom(
$this->getConfigFile(),
'excel'
);
$this->app->bind(CacheManager::class, function ($app) {
return new CacheManager($app);
});
$this->app->singleton(TransactionManager::class, function ($app) {
return new TransactionManager($app);
});
$this->app->bind(TransactionHandler::class, function ($app) {
return $app->make(TransactionManager::class)->driver();
});
$this->app->bind(TemporaryFileFactory::class, function () {
return new TemporaryFileFactory(
config('excel.temporary_files.local_path', config('excel.exports.temp_path', storage_path('framework/laravel-excel'))),
config('excel.temporary_files.remote_disk')
);
});
$this->app->bind(Filesystem::class, function ($app) {
return new Filesystem($app->make('filesystem'));
});
$this->app->bind('excel', function ($app) {
return new Excel(
$app->make(Writer::class),
$app->make(QueuedWriter::class),
$app->make(Reader::class),
$app->make(Filesystem::class)
);
});
$this->app->alias('excel', Excel::class);
$this->app->alias('excel', Exporter::class);
$this->app->alias('excel', Importer::class);
Collection::mixin(new DownloadCollectionMixin);
Collection::mixin(new StoreCollectionMixin);
Builder::macro('downloadExcel', (new DownloadQueryMacro)());
Builder::macro('storeExcel', (new StoreQueryMacro())());
Builder::macro('import', (new ImportMacro())());
Builder::macro('importAs', (new ImportAsMacro())());
$this->commands([
ExportMakeCommand::class,
ImportMakeCommand::class,
]);
}
/**
* @return string
*/
protected function getConfigFile(): string
{
return __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'excel.php';
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Sheet.php | src/Sheet.php | <?php
namespace Maatwebsite\Excel;
use Closure;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromGenerator;
use Maatwebsite\Excel\Concerns\FromIterator;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
use Maatwebsite\Excel\Concerns\WithCharts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithColumnLimit;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithCustomChunkSize;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithDrawings;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithFormatData;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMappedCells;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithProgressBar;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Exceptions\ConcernConflictException;
use Maatwebsite\Excel\Exceptions\RowSkippedException;
use Maatwebsite\Excel\Exceptions\SheetNotFoundException;
use Maatwebsite\Excel\Files\TemporaryFileFactory;
use Maatwebsite\Excel\Helpers\ArrayHelper;
use Maatwebsite\Excel\Helpers\CellHelper;
use Maatwebsite\Excel\Imports\EndRowFinder;
use Maatwebsite\Excel\Imports\HeadingRowExtractor;
use Maatwebsite\Excel\Imports\ModelImporter;
use Maatwebsite\Excel\Validators\RowValidator;
use PhpOffice\PhpSpreadsheet\Cell\Cell as SpreadsheetCell;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Html;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Throwable;
/** @mixin Worksheet */
class Sheet
{
use DelegatedMacroable, HasEventBus;
/**
* @var int
*/
protected $chunkSize;
/**
* @var TemporaryFileFactory
*/
protected $temporaryFileFactory;
/**
* @var object
*/
protected $exportable;
/**
* @var Worksheet
*/
private $worksheet;
/**
* @param Worksheet $worksheet
*/
public function __construct(Worksheet $worksheet)
{
$this->worksheet = $worksheet;
$this->chunkSize = config('excel.exports.chunk_size', 100);
$this->temporaryFileFactory = app(TemporaryFileFactory::class);
}
/**
* @param Spreadsheet $spreadsheet
* @param string|int $index
* @return Sheet
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws SheetNotFoundException
*/
public static function make(Spreadsheet $spreadsheet, $index)
{
if (is_numeric($index)) {
return self::byIndex($spreadsheet, $index);
}
return self::byName($spreadsheet, $index);
}
/**
* @param Spreadsheet $spreadsheet
* @param int $index
* @return Sheet
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws SheetNotFoundException
*/
public static function byIndex(Spreadsheet $spreadsheet, int $index): Sheet
{
if (!isset($spreadsheet->getAllSheets()[$index])) {
throw SheetNotFoundException::byIndex($index, $spreadsheet->getSheetCount());
}
return new static($spreadsheet->getSheet($index));
}
/**
* @param Spreadsheet $spreadsheet
* @param string $name
* @return Sheet
*
* @throws SheetNotFoundException
*/
public static function byName(Spreadsheet $spreadsheet, string $name): Sheet
{
if (!$spreadsheet->sheetNameExists($name)) {
throw SheetNotFoundException::byName($name);
}
return new static($spreadsheet->getSheetByName($name));
}
/**
* @param object $sheetExport
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public function open($sheetExport)
{
$this->exportable = $sheetExport;
if ($sheetExport instanceof WithCustomValueBinder) {
SpreadsheetCell::setValueBinder($sheetExport);
}
if ($sheetExport instanceof WithEvents) {
$this->registerListeners($sheetExport->registerEvents());
}
$this->raise(new BeforeSheet($this, $this->exportable));
if ($sheetExport instanceof WithTitle) {
$title = $sheetExport->title();
$title = str_replace(['*', ':', '/', '\\', '?', '[', ']'], '', $title);
if (StringHelper::countCharacters($title) > Worksheet::SHEET_TITLE_MAXIMUM_LENGTH) {
$title = StringHelper::substring($title, 0, Worksheet::SHEET_TITLE_MAXIMUM_LENGTH);
}
$this->worksheet->setTitle($title);
}
if (($sheetExport instanceof FromQuery || $sheetExport instanceof FromCollection || $sheetExport instanceof FromArray) && $sheetExport instanceof FromView) {
throw ConcernConflictException::queryOrCollectionAndView();
}
if (!$sheetExport instanceof FromView && $sheetExport instanceof WithHeadings) {
if ($sheetExport instanceof WithCustomStartCell) {
$startCell = $sheetExport->startCell();
}
$this->append(
ArrayHelper::ensureMultipleRows($sheetExport->headings()),
$startCell ?? null,
$this->hasStrictNullComparison($sheetExport)
);
}
}
/**
* @param object $sheetExport
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
public function export($sheetExport)
{
$this->open($sheetExport);
if ($sheetExport instanceof FromView) {
$this->fromView($sheetExport);
} else {
if ($sheetExport instanceof FromQuery) {
$this->fromQuery($sheetExport, $this->worksheet);
}
if ($sheetExport instanceof FromCollection) {
$this->fromCollection($sheetExport);
}
if ($sheetExport instanceof FromArray) {
$this->fromArray($sheetExport);
}
if ($sheetExport instanceof FromIterator) {
$this->fromIterator($sheetExport);
}
if ($sheetExport instanceof FromGenerator) {
$this->fromGenerator($sheetExport);
}
}
$this->close($sheetExport);
}
/**
* @param object $import
* @param int $startRow
*/
public function import($import, int $startRow = 1)
{
if ($import instanceof WithEvents) {
$this->registerListeners($import->registerEvents());
}
$this->raise(new BeforeSheet($this, $import));
if ($import instanceof WithProgressBar && !$import instanceof WithChunkReading) {
$import->getConsoleOutput()->progressStart($this->worksheet->getHighestRow());
}
$calculatesFormulas = $import instanceof WithCalculatedFormulas;
$formatData = $import instanceof WithFormatData;
if ($import instanceof WithMappedCells) {
app(MappedReader::class)->map($import, $this->worksheet);
} else {
if ($import instanceof ToModel) {
app(ModelImporter::class)->import($this->worksheet, $import, $startRow);
}
if ($import instanceof ToCollection) {
$rows = $this->toCollection($import, $startRow, null, $calculatesFormulas, $formatData);
if ($import instanceof WithValidation) {
$rows = $this->validated($import, $startRow, $rows);
}
$import->collection($rows);
}
if ($import instanceof ToArray) {
$rows = $this->toArray($import, $startRow, null, $calculatesFormulas, $formatData);
if ($import instanceof WithValidation) {
$rows = $this->validated($import, $startRow, $rows);
}
$import->array($rows);
}
}
if ($import instanceof OnEachRow) {
$headingRow = HeadingRowExtractor::extract($this->worksheet, $import);
$headerIsGrouped = HeadingRowExtractor::extractGrouping($headingRow, $import);
$endColumn = $import instanceof WithColumnLimit ? $import->endColumn() : null;
$preparationCallback = $this->getPreparationCallback($import);
foreach ($this->worksheet->getRowIterator()->resetStart($startRow ?? 1) as $row) {
$sheetRow = new Row($row, $headingRow, $headerIsGrouped);
if ($import instanceof WithValidation) {
$sheetRow->setPreparationCallback($preparationCallback);
}
$rowArray = $sheetRow->toArray(null, $import instanceof WithCalculatedFormulas, $import instanceof WithFormatData, $endColumn);
$rowIsEmptyAccordingToImport = $import instanceof SkipsEmptyRows && method_exists($import, 'isEmptyWhen') && $import->isEmptyWhen($rowArray);
if (!$import instanceof SkipsEmptyRows || ($import instanceof SkipsEmptyRows && (!$rowIsEmptyAccordingToImport && !$sheetRow->isEmpty($calculatesFormulas)))) {
if ($import instanceof WithValidation) {
$toValidate = [$sheetRow->getIndex() => $rowArray];
try {
app(RowValidator::class)->validate($toValidate, $import);
$import->onRow($sheetRow);
} catch (RowSkippedException $e) {
} catch (Throwable $e) {
if ($import instanceof SkipsOnError) {
$import->onError($e);
} else {
throw $e;
}
}
} else {
try {
$import->onRow($sheetRow);
} catch (Throwable $e) {
if ($import instanceof SkipsOnError) {
$import->onError($e);
} else {
throw $e;
}
}
}
}
if ($import instanceof WithProgressBar) {
$import->getConsoleOutput()->progressAdvance();
}
}
}
$this->raise(new AfterSheet($this, $import));
if ($import instanceof WithProgressBar && !$import instanceof WithChunkReading) {
$import->getConsoleOutput()->progressFinish();
}
}
/**
* @param object $import
* @param int|null $startRow
* @param null $nullValue
* @param bool $calculateFormulas
* @param bool $formatData
* @return array
*/
public function toArray($import, ?int $startRow = null, $nullValue = null, $calculateFormulas = false, $formatData = false)
{
if ($startRow > $this->worksheet->getHighestRow()) {
return [];
}
$endRow = EndRowFinder::find($import, $startRow, $this->worksheet->getHighestRow());
$headingRow = HeadingRowExtractor::extract($this->worksheet, $import);
$headerIsGrouped = HeadingRowExtractor::extractGrouping($headingRow, $import);
$endColumn = $import instanceof WithColumnLimit ? $import->endColumn() : null;
$rows = [];
foreach ($this->worksheet->getRowIterator($startRow, $endRow) as $index => $row) {
$row = new Row($row, $headingRow, $headerIsGrouped);
if ($import instanceof SkipsEmptyRows && $row->isEmpty($calculateFormulas, $endColumn)) {
continue;
}
$row = $row->toArray($nullValue, $calculateFormulas, $formatData, $endColumn);
if ($import && method_exists($import, 'isEmptyWhen') && $import->isEmptyWhen($row)) {
continue;
}
if ($import instanceof WithMapping) {
$row = $import->map($row);
}
if ($import instanceof WithValidation && method_exists($import, 'prepareForValidation')) {
$row = $import->prepareForValidation($row, $index);
}
$rows[] = $row;
if ($import instanceof WithProgressBar) {
$import->getConsoleOutput()->progressAdvance();
}
}
return $rows;
}
/**
* @param object $import
* @param int|null $startRow
* @param null $nullValue
* @param bool $calculateFormulas
* @param bool $formatData
* @return Collection
*/
public function toCollection($import, ?int $startRow = null, $nullValue = null, $calculateFormulas = false, $formatData = false): Collection
{
$rows = $this->toArray($import, $startRow, $nullValue, $calculateFormulas, $formatData);
return new Collection(array_map(function (array $row) {
return new Collection($row);
}, $rows));
}
/**
* @param object $sheetExport
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public function close($sheetExport)
{
if ($sheetExport instanceof WithCharts) {
$this->addCharts($sheetExport->charts());
}
if ($sheetExport instanceof WithDrawings) {
$this->addDrawings($sheetExport->drawings());
}
$this->exportable = $sheetExport;
if ($sheetExport instanceof WithColumnFormatting) {
foreach ($sheetExport->columnFormats() as $column => $format) {
$this->formatColumn($column, $format);
}
}
if ($sheetExport instanceof ShouldAutoSize) {
$this->autoSize();
}
if ($sheetExport instanceof WithColumnWidths) {
foreach ($sheetExport->columnWidths() as $column => $width) {
$this->worksheet->getColumnDimension($column)->setAutoSize(false)->setWidth($width);
}
}
if ($sheetExport instanceof WithStyles) {
$styles = $sheetExport->styles($this->worksheet);
if (is_array($styles)) {
foreach ($styles as $coordinate => $coordinateStyles) {
if (is_numeric($coordinate)) {
$coordinate = 'A' . $coordinate . ':' . $this->worksheet->getHighestColumn($coordinate) . $coordinate;
}
$this->worksheet->getStyle($coordinate)->applyFromArray($coordinateStyles);
}
}
}
$this->raise(new AfterSheet($this, $this->exportable));
$this->clearListeners();
}
/**
* @param FromView $sheetExport
* @param int|null $sheetIndex
*
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
public function fromView(FromView $sheetExport, $sheetIndex = null)
{
$temporaryFile = $this->temporaryFileFactory->makeLocal(null, 'html');
$temporaryFile->put($sheetExport->view()->render());
$spreadsheet = $this->worksheet->getParent();
/** @var Html $reader */
$reader = IOFactory::createReader('Html');
// If no sheetIndex given, insert content into the last sheet
$reader->setSheetIndex($sheetIndex ?? $spreadsheet->getSheetCount() - 1);
$reader->loadIntoExisting($temporaryFile->getLocalPath(), $spreadsheet);
$temporaryFile->delete();
}
/**
* @param FromQuery $sheetExport
* @param Worksheet $worksheet
*/
public function fromQuery(FromQuery $sheetExport, Worksheet $worksheet)
{
$query = $sheetExport->query();
if ($query instanceof \Laravel\Scout\Builder) {
$this->fromScout($sheetExport, $worksheet);
return;
}
//Operate on a clone to avoid altering the original
//and use the clone operator directly to support old versions of Laravel
//that don't have a clone method in eloquent
$clonedQuery = clone $query;
$clonedQuery->chunk($this->getChunkSize($sheetExport), function ($chunk) use ($sheetExport) {
$this->appendRows($chunk, $sheetExport);
});
}
/**
* @param FromQuery $sheetExport
* @param Worksheet $worksheet
*/
public function fromScout(FromQuery $sheetExport, Worksheet $worksheet)
{
$scout = $sheetExport->query();
$chunkSize = $this->getChunkSize($sheetExport);
$chunk = $scout->paginate($chunkSize);
// Append first page
$this->appendRows($chunk->items(), $sheetExport);
// Append rest of pages
for ($page = 2; $page <= $chunk->lastPage(); $page++) {
$this->appendRows($scout->paginate($chunkSize, 'page', $page)->items(), $sheetExport);
}
}
/**
* @param FromCollection $sheetExport
*/
public function fromCollection(FromCollection $sheetExport)
{
$this->appendRows($sheetExport->collection()->all(), $sheetExport);
}
/**
* @param FromArray $sheetExport
*/
public function fromArray(FromArray $sheetExport)
{
$this->appendRows($sheetExport->array(), $sheetExport);
}
/**
* @param FromIterator $sheetExport
*/
public function fromIterator(FromIterator $sheetExport)
{
$iterator = class_exists(LazyCollection::class) ? new LazyCollection(function () use ($sheetExport) {
foreach ($sheetExport->iterator() as $row) {
yield $row;
}
}) : $sheetExport->iterator();
$this->appendRows($iterator, $sheetExport);
}
/**
* @param FromGenerator $sheetExport
*/
public function fromGenerator(FromGenerator $sheetExport)
{
$generator = class_exists(LazyCollection::class) ? new LazyCollection(function () use ($sheetExport) {
foreach ($sheetExport->generator() as $row) {
yield $row;
}
}) : $sheetExport->generator();
$this->appendRows($generator, $sheetExport);
}
/**
* @param array $rows
* @param string|null $startCell
* @param bool $strictNullComparison
*/
public function append(array $rows, ?string $startCell = null, bool $strictNullComparison = false)
{
if (!$startCell) {
$startCell = 'A1';
}
if ($this->hasRows()) {
$startCell = CellHelper::getColumnFromCoordinate($startCell) . ($this->worksheet->getHighestRow() + 1);
}
$this->worksheet->fromArray($rows, null, $startCell, $strictNullComparison);
}
public function autoSize()
{
foreach ($this->buildColumnRange('A', $this->worksheet->getHighestDataColumn()) as $col) {
$dimension = $this->worksheet->getColumnDimension($col);
// Only auto-size columns that have not have an explicit width.
if ($dimension->getWidth() == -1) {
$dimension->setAutoSize(true);
}
}
}
/**
* @param string $column
* @param string $format
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public function formatColumn(string $column, string $format)
{
// If the column is a range, we wouldn't need to calculate the range.
if (stripos($column, ':') !== false) {
$this->worksheet
->getStyle($column)
->getNumberFormat()
->setFormatCode($format);
} else {
$this->worksheet
->getStyle($column . '1:' . $column . $this->worksheet->getHighestRow())
->getNumberFormat()
->setFormatCode($format);
}
}
/**
* @param int $chunkSize
* @return Sheet
*/
public function chunkSize(int $chunkSize)
{
$this->chunkSize = $chunkSize;
return $this;
}
/**
* @return Worksheet
*/
public function getDelegate()
{
return $this->worksheet;
}
/**
* @param Chart|Chart[] $charts
*/
public function addCharts($charts)
{
$charts = \is_array($charts) ? $charts : [$charts];
foreach ($charts as $chart) {
$this->worksheet->addChart($chart);
}
}
/**
* @param BaseDrawing|BaseDrawing[] $drawings
*/
public function addDrawings($drawings)
{
$drawings = \is_array($drawings) ? $drawings : [$drawings];
foreach ($drawings as $drawing) {
$drawing->setWorksheet($this->worksheet);
}
}
/**
* @param string $concern
* @return string
*/
public function hasConcern(string $concern): string
{
return $this->exportable instanceof $concern;
}
/**
* @param iterable $rows
* @param object $sheetExport
*/
public function appendRows($rows, $sheetExport)
{
if (method_exists($sheetExport, 'prepareRows')) {
$rows = $sheetExport->prepareRows($rows);
}
$rows = $rows instanceof LazyCollection ? $rows : new Collection($rows);
$rows->flatMap(function ($row) use ($sheetExport) {
if ($sheetExport instanceof WithMapping) {
$row = $sheetExport->map($row);
}
if ($sheetExport instanceof WithCustomValueBinder) {
SpreadsheetCell::setValueBinder($sheetExport);
}
return ArrayHelper::ensureMultipleRows(
static::mapArraybleRow($row)
);
})->chunk(1000)->each(function ($rows) use ($sheetExport) {
$this->append(
$rows->toArray(),
$sheetExport instanceof WithCustomStartCell ? $sheetExport->startCell() : null,
$this->hasStrictNullComparison($sheetExport)
);
});
}
/**
* @param mixed $row
* @return array
*/
public static function mapArraybleRow($row): array
{
// When dealing with eloquent models, we'll skip the relations
// as we won't be able to display them anyway.
if (is_object($row) && method_exists($row, 'attributesToArray')) {
return $row->attributesToArray();
}
if ($row instanceof Arrayable) {
return $row->toArray();
}
// Convert StdObjects to arrays
if (is_object($row)) {
return json_decode(json_encode($row), true);
}
return $row;
}
/**
* @param $sheetImport
* @return int
*/
public function getStartRow($sheetImport): int
{
return HeadingRowExtractor::determineStartRow($sheetImport);
}
/**
* Disconnect the sheet.
*/
public function disconnect()
{
$this->worksheet->disconnectCells();
unset($this->worksheet);
}
/**
* @return Collection|array
*/
protected function validated(WithValidation $import, int $startRow, $rows)
{
$toValidate = (new Collection($rows))->mapWithKeys(function ($row, $index) use ($startRow) {
return [($startRow + $index) => $row];
});
try {
app(RowValidator::class)->validate($toValidate->toArray(), $import);
} catch (RowSkippedException $e) {
foreach ($e->skippedRows() as $row) {
unset($rows[$row - $startRow]);
}
}
return $rows;
}
/**
* @param string $lower
* @param string $upper
* @return \Generator
*/
protected function buildColumnRange(string $lower, string $upper)
{
$upper++;
for ($i = $lower; $i !== $upper; $i++) {
yield $i;
}
}
/**
* @return bool
*/
private function hasRows(): bool
{
$startCell = 'A1';
if ($this->exportable instanceof WithCustomStartCell) {
$startCell = $this->exportable->startCell();
}
return $this->worksheet->cellExists($startCell);
}
/**
* @param object $sheetExport
* @return bool
*/
private function hasStrictNullComparison($sheetExport): bool
{
if ($sheetExport instanceof WithStrictNullComparison) {
return true;
}
return config('excel.exports.strict_null_comparison', false);
}
/**
* @param object|WithCustomChunkSize $export
* @return int
*/
private function getChunkSize($export): int
{
if ($export instanceof WithCustomChunkSize) {
return $export->chunkSize();
}
return $this->chunkSize;
}
/**
* @param object|WithValidation $import
* @return Closure|null
*/
private function getPreparationCallback($import)
{
if (!$import instanceof WithValidation || !method_exists($import, 'prepareForValidation')) {
return null;
}
return function (array $data, int $index) use ($import) {
return $import->prepareForValidation($data, $index);
};
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/DefaultValueBinder.php | src/DefaultValueBinder.php | <?php
namespace Maatwebsite\Excel;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder as PhpSpreadsheetDefaultValueBinder;
class DefaultValueBinder extends PhpSpreadsheetDefaultValueBinder
{
/**
* @param Cell $cell Cell to bind value to
* @param mixed $value Value to bind in cell
* @return bool
*/
public function bindValue(Cell $cell, $value)
{
if (is_array($value)) {
$value = \json_encode($value);
}
return parent::bindValue($cell, $value);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/HeadingRowImport.php | src/HeadingRowImport.php | <?php
namespace Maatwebsite\Excel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithLimit;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
class HeadingRowImport implements WithStartRow, WithLimit, WithMapping
{
use Importable;
/**
* @var int
*/
private $headingRow;
/**
* @param int $headingRow
*/
public function __construct(int $headingRow = 1)
{
$this->headingRow = $headingRow;
}
/**
* @return int
*/
public function startRow(): int
{
return $this->headingRow;
}
/**
* @return int
*/
public function limit(): int
{
return 1;
}
/**
* @param mixed $row
* @return array
*/
public function map($row): array
{
return HeadingRowFormatter::format($row);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/RegistersCustomConcerns.php | src/RegistersCustomConcerns.php | <?php
namespace Maatwebsite\Excel;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Events\BeforeWriting;
use Maatwebsite\Excel\Events\Event;
trait RegistersCustomConcerns
{
/**
* @var array
*/
private static $eventMap = [
BeforeWriting::class => Writer::class,
BeforeExport::class => Writer::class,
BeforeSheet::class => Sheet::class,
AfterSheet::class => Sheet::class,
];
/**
* @param string $concern
* @param callable $handler
* @param string $event
*/
public static function extend(string $concern, callable $handler, string $event = BeforeWriting::class)
{
/** @var HasEventBus $delegate */
$delegate = static::$eventMap[$event] ?? BeforeWriting::class;
$delegate::listen($event, function (Event $event) use ($concern, $handler) {
if ($event->appliesToConcern($concern)) {
$handler($event->getConcernable(), $event->getDelegate());
}
});
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Files/TemporaryFileFactory.php | src/Files/TemporaryFileFactory.php | <?php
namespace Maatwebsite\Excel\Files;
use Illuminate\Support\Str;
class TemporaryFileFactory
{
/**
* @var string|null
*/
private $temporaryPath;
/**
* @var string|null
*/
private $temporaryDisk;
/**
* @param string|null $temporaryPath
* @param string|null $temporaryDisk
*/
public function __construct(?string $temporaryPath = null, ?string $temporaryDisk = null)
{
$this->temporaryPath = $temporaryPath;
$this->temporaryDisk = $temporaryDisk;
}
/**
* @param string|null $fileExtension
* @return TemporaryFile
*/
public function make(?string $fileExtension = null): TemporaryFile
{
if (null !== $this->temporaryDisk) {
return $this->makeRemote($fileExtension);
}
return $this->makeLocal(null, $fileExtension);
}
/**
* @param string|null $fileName
* @param string|null $fileExtension
* @return LocalTemporaryFile
*/
public function makeLocal(?string $fileName = null, ?string $fileExtension = null): LocalTemporaryFile
{
if (!file_exists($this->temporaryPath) && !mkdir($concurrentDirectory = $this->temporaryPath, config('excel.temporary_files.local_permissions.dir', 0777), true) && !is_dir($concurrentDirectory)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
}
return new LocalTemporaryFile(
$this->temporaryPath . DIRECTORY_SEPARATOR . ($fileName ?: $this->generateFilename($fileExtension))
);
}
/**
* @param string|null $fileExtension
* @return RemoteTemporaryFile
*/
private function makeRemote(?string $fileExtension = null): RemoteTemporaryFile
{
$filename = $this->generateFilename($fileExtension);
return new RemoteTemporaryFile(
$this->temporaryDisk,
config('excel.temporary_files.remote_prefix') . $filename,
$this->makeLocal($filename)
);
}
/**
* @param string|null $fileExtension
* @return string
*/
private function generateFilename(?string $fileExtension = null): string
{
return 'laravel-excel-' . Str::random(32) . ($fileExtension ? '.' . $fileExtension : '');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Files/Filesystem.php | src/Files/Filesystem.php | <?php
namespace Maatwebsite\Excel\Files;
use Illuminate\Contracts\Filesystem\Factory;
class Filesystem
{
/**
* @var Factory
*/
private $filesystem;
/**
* @param Factory $filesystem
*/
public function __construct(Factory $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* @param string|null $disk
* @param array $diskOptions
* @return Disk
*/
public function disk(?string $disk = null, array $diskOptions = []): Disk
{
return new Disk(
$this->filesystem->disk($disk),
$disk,
$diskOptions
);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Files/LocalTemporaryFile.php | src/Files/LocalTemporaryFile.php | <?php
namespace Maatwebsite\Excel\Files;
class LocalTemporaryFile extends TemporaryFile
{
/**
* @var string
*/
private $filePath;
/**
* @param string $filePath
*/
public function __construct(string $filePath)
{
touch($filePath);
if (($rights = config('excel.temporary_files.local_permissions.file', null)) !== null) {
chmod($filePath, $rights);
}
$this->filePath = realpath($filePath);
}
/**
* @return string
*/
public function getLocalPath(): string
{
return $this->filePath;
}
/**
* @return bool
*/
public function exists(): bool
{
return file_exists($this->filePath);
}
/**
* @return bool
*/
public function delete(): bool
{
if (@unlink($this->filePath) || !$this->exists()) {
return true;
}
return unlink($this->filePath);
}
/**
* @return resource
*/
public function readStream()
{
return fopen($this->getLocalPath(), 'rb+');
}
/**
* @return string
*/
public function contents(): string
{
return file_get_contents($this->filePath);
}
/**
* @param @param string|resource $contents
*/
public function put($contents)
{
file_put_contents($this->filePath, $contents);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Files/Disk.php | src/Files/Disk.php | <?php
namespace Maatwebsite\Excel\Files;
use Illuminate\Contracts\Filesystem\Filesystem as IlluminateFilesystem;
/**
* @method bool get(string $filename)
* @method resource readStream(string $filename)
* @method bool delete(string $filename)
* @method bool exists(string $filename)
*/
class Disk
{
/**
* @var IlluminateFilesystem
*/
protected $disk;
/**
* @var string|null
*/
protected $name;
/**
* @var array
*/
protected $diskOptions;
/**
* @param IlluminateFilesystem $disk
* @param string|null $name
* @param array $diskOptions
*/
public function __construct(IlluminateFilesystem $disk, ?string $name = null, array $diskOptions = [])
{
$this->disk = $disk;
$this->name = $name;
$this->diskOptions = $diskOptions;
}
/**
* @param string $name
* @param array $arguments
* @return mixed
*/
public function __call($name, $arguments)
{
return $this->disk->{$name}(...$arguments);
}
/**
* @param string $destination
* @param string|resource $contents
* @return bool
*/
public function put(string $destination, $contents): bool
{
return $this->disk->put($destination, $contents, $this->diskOptions);
}
/**
* @param TemporaryFile $source
* @param string $destination
* @return bool
*/
public function copy(TemporaryFile $source, string $destination): bool
{
$readStream = $source->readStream();
if (!is_resource($readStream)) {
return false;
}
if (realpath($destination)) {
$tempStream = fopen($destination, 'rb+');
$success = stream_copy_to_stream($readStream, $tempStream) !== false;
if (is_resource($tempStream)) {
fclose($tempStream);
}
} else {
$success = $this->put($destination, $readStream);
}
if (is_resource($readStream)) {
fclose($readStream);
}
return $success;
}
/**
* @param string $filename
*/
public function touch(string $filename)
{
$this->disk->put($filename, '', $this->diskOptions);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Files/RemoteTemporaryFile.php | src/Files/RemoteTemporaryFile.php | <?php
namespace Maatwebsite\Excel\Files;
use Illuminate\Support\Arr;
class RemoteTemporaryFile extends TemporaryFile
{
/**
* @var string
*/
private $disk;
/**
* @var Disk|null
*/
private $diskInstance;
/**
* @var string
*/
private $filename;
/**
* @var LocalTemporaryFile
*/
private $localTemporaryFile;
/**
* @param string $disk
* @param string $filename
* @param LocalTemporaryFile $localTemporaryFile
*/
public function __construct(string $disk, string $filename, LocalTemporaryFile $localTemporaryFile)
{
$this->disk = $disk;
$this->filename = $filename;
$this->localTemporaryFile = $localTemporaryFile;
$this->disk()->touch($filename);
}
public function __sleep()
{
return ['disk', 'filename', 'localTemporaryFile'];
}
/**
* @return string
*/
public function getLocalPath(): string
{
return $this->localTemporaryFile->getLocalPath();
}
/**
* @return bool
*/
public function existsLocally(): bool
{
return $this->localTemporaryFile->exists();
}
/**
* @return bool
*/
public function exists(): bool
{
return $this->disk()->exists($this->filename);
}
/**
* @return bool
*/
public function deleteLocalCopy(): bool
{
return $this->localTemporaryFile->delete();
}
/**
* @return bool
*/
public function delete(): bool
{
// we don't need to delete local copy as it's deleted at end of each chunk
if (!config('excel.temporary_files.force_resync_remote')) {
$this->deleteLocalCopy();
}
return $this->disk()->delete($this->filename);
}
/**
* @return TemporaryFile
*/
public function sync(bool $copy = true): TemporaryFile
{
if (!$this->localTemporaryFile->exists()) {
$this->localTemporaryFile = resolve(TemporaryFileFactory::class)
->makeLocal(Arr::last(explode('/', $this->filename)));
}
$copy && $this->disk()->copy(
$this,
$this->localTemporaryFile->getLocalPath()
);
return $this;
}
/**
* Store on remote disk.
*/
public function updateRemote()
{
$this->disk()->copy(
$this->localTemporaryFile,
$this->filename
);
}
/**
* @return resource
*/
public function readStream()
{
return $this->disk()->readStream($this->filename);
}
/**
* @return string
*/
public function contents(): string
{
return $this->disk()->get($this->filename);
}
/**
* @param string|resource $contents
*/
public function put($contents)
{
$this->disk()->put($this->filename, $contents);
}
/**
* @return Disk
*/
public function disk(): Disk
{
return $this->diskInstance ?: $this->diskInstance = app(Filesystem::class)->disk($this->disk);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Files/TemporaryFile.php | src/Files/TemporaryFile.php | <?php
namespace Maatwebsite\Excel\Files;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
abstract class TemporaryFile
{
/**
* @return string
*/
abstract public function getLocalPath(): string;
/**
* @return bool
*/
abstract public function exists(): bool;
/**
* @param @param string|resource $contents
*/
abstract public function put($contents);
/**
* @return bool
*/
abstract public function delete(): bool;
/**
* @return resource
*/
abstract public function readStream();
/**
* @return string
*/
abstract public function contents(): string;
/**
* @return TemporaryFile
*/
public function sync(): TemporaryFile
{
return $this;
}
/**
* @param string|UploadedFile $filePath
* @param string|null $disk
* @return TemporaryFile
*/
public function copyFrom($filePath, ?string $disk = null): TemporaryFile
{
if ($filePath instanceof UploadedFile) {
$readStream = fopen($filePath->getRealPath(), 'rb');
} elseif ($disk === null && realpath($filePath) !== false) {
$readStream = fopen($filePath, 'rb');
} else {
$diskInstance = app('filesystem')->disk($disk);
if (!$diskInstance->exists($filePath)) {
$logPath = '[' . $filePath . ']';
if ($disk) {
$logPath .= ' (' . $disk . ')';
}
throw new FileNotFoundException('File ' . $logPath . ' does not exist and can therefore not be imported.');
}
$readStream = $diskInstance->readStream($filePath);
}
$this->put($readStream);
if (is_resource($readStream)) {
fclose($readStream);
}
return $this->sync();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/CloseSheet.php | src/Jobs/CloseSheet.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Writer;
class CloseSheet implements ShouldQueue
{
use Queueable, ProxyFailures;
/**
* @var object
*/
private $sheetExport;
/**
* @var string
*/
private $temporaryFile;
/**
* @var string
*/
private $writerType;
/**
* @var int
*/
private $sheetIndex;
/**
* @param object $sheetExport
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @param int $sheetIndex
*/
public function __construct($sheetExport, TemporaryFile $temporaryFile, string $writerType, int $sheetIndex)
{
$this->sheetExport = $sheetExport;
$this->temporaryFile = $temporaryFile;
$this->writerType = $writerType;
$this->sheetIndex = $sheetIndex;
}
/**
* @param Writer $writer
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
public function handle(Writer $writer)
{
$writer = $writer->reopen(
$this->temporaryFile,
$this->writerType
);
$sheet = $writer->getSheetByIndex($this->sheetIndex);
if ($this->sheetExport instanceof WithEvents) {
$sheet->registerListeners($this->sheetExport->registerEvents());
}
$sheet->close($this->sheetExport);
$writer->write(
$this->sheetExport,
$this->temporaryFile,
$this->writerType
);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/AppendQueryToSheet.php | src/Jobs/AppendQueryToSheet.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterChunk;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\HasEventBus;
use Maatwebsite\Excel\Jobs\Middleware\LocalizeJob;
use Maatwebsite\Excel\Writer;
class AppendQueryToSheet implements ShouldQueue
{
use Queueable, Dispatchable, ProxyFailures, InteractsWithQueue, HasEventBus;
/**
* @var TemporaryFile
*/
public $temporaryFile;
/**
* @var string
*/
public $writerType;
/**
* @var int
*/
public $sheetIndex;
/**
* @var FromQuery
*/
public $sheetExport;
/**
* @var int
*/
public $page;
/**
* @var int
*/
public $chunkSize;
/**
* @param FromQuery $sheetExport
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @param int $sheetIndex
* @param int $page
* @param int $chunkSize
*/
public function __construct(
FromQuery $sheetExport,
TemporaryFile $temporaryFile,
string $writerType,
int $sheetIndex,
int $page,
int $chunkSize
) {
$this->sheetExport = $sheetExport;
$this->temporaryFile = $temporaryFile;
$this->writerType = $writerType;
$this->sheetIndex = $sheetIndex;
$this->page = $page;
$this->chunkSize = $chunkSize;
}
/**
* Get the middleware the job should be dispatched through.
*
* @return array
*/
public function middleware()
{
return (method_exists($this->sheetExport, 'middleware')) ? $this->sheetExport->middleware() : [];
}
/**
* @param Writer $writer
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
public function handle(Writer $writer)
{
(new LocalizeJob($this->sheetExport))->handle($this, function () use ($writer) {
if ($this->sheetExport instanceof WithEvents) {
$this->registerListeners($this->sheetExport->registerEvents());
}
$writer = $writer->reopen($this->temporaryFile, $this->writerType);
$sheet = $writer->getSheetByIndex($this->sheetIndex);
$query = $this->sheetExport->query()->forPage($this->page, $this->chunkSize);
$sheet->appendRows($query->get(), $this->sheetExport);
$writer->write($this->sheetExport, $this->temporaryFile, $this->writerType);
$this->raise(new AfterChunk($sheet, $this->sheetExport, ($this->page - 1) * $this->chunkSize));
$this->clearListeners();
});
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/QueueImport.php | src/Jobs/QueueImport.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class QueueImport implements ShouldQueue
{
use ExtendedQueueable, Dispatchable;
/**
* @var int
*/
public $tries;
/**
* @var int
*/
public $timeout;
/**
* @param ShouldQueue $import
*/
public function __construct(?ShouldQueue $import = null)
{
if ($import) {
$this->timeout = $import->timeout ?? null;
$this->tries = $import->tries ?? null;
}
}
public function handle()
{
//
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/AppendDataToSheet.php | src/Jobs/AppendDataToSheet.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Jobs\Middleware\LocalizeJob;
use Maatwebsite\Excel\Writer;
class AppendDataToSheet implements ShouldQueue
{
use Queueable, Dispatchable, ProxyFailures, InteractsWithQueue;
/**
* @var array
*/
public $data = [];
/**
* @var string
*/
public $temporaryFile;
/**
* @var string
*/
public $writerType;
/**
* @var int
*/
public $sheetIndex;
/**
* @var object
*/
public $sheetExport;
/**
* @param object $sheetExport
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @param int $sheetIndex
* @param array $data
*/
public function __construct($sheetExport, TemporaryFile $temporaryFile, string $writerType, int $sheetIndex, array $data)
{
$this->sheetExport = $sheetExport;
$this->data = $data;
$this->temporaryFile = $temporaryFile;
$this->writerType = $writerType;
$this->sheetIndex = $sheetIndex;
}
/**
* Get the middleware the job should be dispatched through.
*
* @return array
*/
public function middleware()
{
return (method_exists($this->sheetExport, 'middleware')) ? $this->sheetExport->middleware() : [];
}
/**
* @param Writer $writer
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
public function handle(Writer $writer)
{
(new LocalizeJob($this->sheetExport))->handle($this, function () use ($writer) {
$writer = $writer->reopen($this->temporaryFile, $this->writerType);
$sheet = $writer->getSheetByIndex($this->sheetIndex);
$sheet->appendRows($this->data, $this->sheetExport);
$writer->write($this->sheetExport, $this->temporaryFile, $this->writerType);
});
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/AppendPaginatedToSheet.php | src/Jobs/AppendPaginatedToSheet.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Laravel\Scout\Builder as ScoutBuilder;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Jobs\Middleware\LocalizeJob;
use Maatwebsite\Excel\Writer;
class AppendPaginatedToSheet implements ShouldQueue
{
use Queueable, Dispatchable, ProxyFailures, InteractsWithQueue;
/**
* @var TemporaryFile
*/
public $temporaryFile;
/**
* @var string
*/
public $writerType;
/**
* @var int
*/
public $sheetIndex;
/**
* @var FromQuery
*/
public $sheetExport;
/**
* @var int
*/
public $page;
/**
* @var int
*/
public $perPage;
/**
* @param FromQuery $sheetExport
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @param int $sheetIndex
* @param int $page
* @param int $perPage
*/
public function __construct(
FromQuery $sheetExport,
TemporaryFile $temporaryFile,
string $writerType,
int $sheetIndex,
int $page,
int $perPage
) {
$this->sheetExport = $sheetExport;
$this->temporaryFile = $temporaryFile;
$this->writerType = $writerType;
$this->sheetIndex = $sheetIndex;
$this->page = $page;
$this->perPage = $perPage;
}
/**
* Get the middleware the job should be dispatched through.
*
* @return array
*/
public function middleware()
{
return (method_exists($this->sheetExport, 'middleware')) ? $this->sheetExport->middleware() : [];
}
/**
* @param Writer $writer
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
public function handle(Writer $writer)
{
(new LocalizeJob($this->sheetExport))->handle($this, function () use ($writer) {
$writer = $writer->reopen($this->temporaryFile, $this->writerType);
$sheet = $writer->getSheetByIndex($this->sheetIndex);
$sheet->appendRows($this->chunk($this->sheetExport->query()), $this->sheetExport);
$writer->write($this->sheetExport, $this->temporaryFile, $this->writerType);
});
}
/**
* @param Builder|Relation|EloquentBuilder|ScoutBuilder $query
*/
protected function chunk($query)
{
if ($query instanceof \Laravel\Scout\Builder) {
return $query->paginate($this->perPage, 'page', $this->page)->items();
}
// Fallback
return $query->forPage($this->page, $this->perPage)->get();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/ExtendedQueueable.php | src/Jobs/ExtendedQueueable.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Bus\Queueable;
trait ExtendedQueueable
{
use Queueable {
chain as originalChain;
}
/**
* @param $chain
* @return $this
*/
public function chain($chain)
{
collect($chain)->each(function ($job) {
$serialized = method_exists($this, 'serializeJob') ? $this->serializeJob($job) : serialize($job);
$this->chained[] = $serialized;
});
return $this;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/AfterImportJob.php | src/Jobs/AfterImportJob.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\ImportFailed;
use Maatwebsite\Excel\HasEventBus;
use Maatwebsite\Excel\Reader;
use Throwable;
class AfterImportJob implements ShouldQueue
{
use HasEventBus, InteractsWithQueue, Queueable;
/**
* @var WithEvents
*/
private $import;
/**
* @var Reader
*/
private $reader;
/**
* @var iterable
*/
private $dependencyIds = [];
private $interval = 60;
/**
* @param object $import
* @param Reader $reader
*/
public function __construct($import, Reader $reader)
{
$this->import = $import;
$this->reader = $reader;
}
public function setInterval(int $interval)
{
$this->interval = $interval;
}
public function setDependencies(Collection $jobs)
{
$this->dependencyIds = $jobs->map(function (ReadChunk $job) {
return $job->getUniqueId();
})->all();
}
public function handle()
{
foreach ($this->dependencyIds as $id) {
if (!ReadChunk::isComplete($id)) {
// Until there is no jobs left to run we put this job back into the queue every minute
// Note: this will do nothing in a SyncQueue but that's desired, because in a SyncQueue jobs run in order
$this->release($this->interval);
return;
}
}
if ($this->import instanceof ShouldQueue && $this->import instanceof WithEvents) {
$this->reader->clearListeners();
$this->reader->registerListeners($this->import->registerEvents());
}
$this->reader->afterImport($this->import);
}
/**
* @param Throwable $e
*/
public function failed(Throwable $e)
{
if ($this->import instanceof WithEvents) {
$this->registerListeners($this->import->registerEvents());
$this->raise(new ImportFailed($e));
if (method_exists($this->import, 'failed')) {
$this->import->failed($e);
}
}
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/ProxyFailures.php | src/Jobs/ProxyFailures.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Throwable;
trait ProxyFailures
{
/**
* @param Throwable $e
*/
public function failed(Throwable $e)
{
if (method_exists($this->sheetExport, 'failed')) {
$this->sheetExport->failed($e);
}
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/QueueExport.php | src/Jobs/QueueExport.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Exceptions\NoSheetsFoundException;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Jobs\Middleware\LocalizeJob;
use Maatwebsite\Excel\Writer;
use Throwable;
class QueueExport implements ShouldQueue
{
use ExtendedQueueable, Dispatchable, InteractsWithQueue;
/**
* @var object
*/
public $export;
/**
* @var string
*/
private $writerType;
/**
* @var TemporaryFile
*/
private $temporaryFile;
/**
* @param object $export
* @param TemporaryFile $temporaryFile
* @param string $writerType
*/
public function __construct($export, TemporaryFile $temporaryFile, string $writerType)
{
$this->export = $export;
$this->writerType = $writerType;
$this->temporaryFile = $temporaryFile;
}
/**
* Get the middleware the job should be dispatched through.
*
* @return array
*/
public function middleware()
{
return (method_exists($this->export, 'middleware')) ? $this->export->middleware() : [];
}
/**
* @param Writer $writer
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public function handle(Writer $writer)
{
(new LocalizeJob($this->export))->handle($this, function () use ($writer) {
$writer->open($this->export);
$sheetExports = [$this->export];
if ($this->export instanceof WithMultipleSheets) {
$sheetExports = $this->export->sheets();
}
if (count($sheetExports) === 0) {
throw new NoSheetsFoundException('Your export did not return any sheet export instances, please make sure your sheets() method always at least returns one instance.');
}
// Pre-create the worksheets
foreach ($sheetExports as $sheetIndex => $sheetExport) {
$sheet = $writer->addNewSheet($sheetIndex);
$sheet->open($sheetExport);
}
// Write to temp file with empty sheets.
$writer->write($sheetExport, $this->temporaryFile, $this->writerType);
});
}
/**
* @param Throwable $e
*/
public function failed(Throwable $e)
{
if (method_exists($this->export, 'failed')) {
$this->export->failed($e);
}
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/StoreQueuedExport.php | src/Jobs/StoreQueuedExport.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Files\Filesystem;
use Maatwebsite\Excel\Files\TemporaryFile;
class StoreQueuedExport implements ShouldQueue
{
use Queueable;
/**
* @var string
*/
private $filePath;
/**
* @var string|null
*/
private $disk;
/**
* @var TemporaryFile
*/
private $temporaryFile;
/**
* @var array|string
*/
private $diskOptions;
/**
* @param TemporaryFile $temporaryFile
* @param string $filePath
* @param string|null $disk
* @param array|string $diskOptions
*/
public function __construct(TemporaryFile $temporaryFile, string $filePath, ?string $disk = null, $diskOptions = [])
{
$this->disk = $disk;
$this->filePath = $filePath;
$this->temporaryFile = $temporaryFile;
$this->diskOptions = $diskOptions;
}
/**
* @param Filesystem $filesystem
*/
public function handle(Filesystem $filesystem)
{
$filesystem->disk($this->disk, $this->diskOptions)->copy(
$this->temporaryFile,
$this->filePath
);
$this->temporaryFile->delete();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/AppendViewToSheet.php | src/Jobs/AppendViewToSheet.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Jobs\Middleware\LocalizeJob;
use Maatwebsite\Excel\Writer;
class AppendViewToSheet implements ShouldQueue
{
use Queueable, Dispatchable, InteractsWithQueue;
/**
* @var TemporaryFile
*/
public $temporaryFile;
/**
* @var string
*/
public $writerType;
/**
* @var int
*/
public $sheetIndex;
/**
* @var FromView
*/
public $sheetExport;
/**
* @param FromView $sheetExport
* @param TemporaryFile $temporaryFile
* @param string $writerType
* @param int $sheetIndex
* @param array $data
*/
public function __construct(FromView $sheetExport, TemporaryFile $temporaryFile, string $writerType, int $sheetIndex)
{
$this->sheetExport = $sheetExport;
$this->temporaryFile = $temporaryFile;
$this->writerType = $writerType;
$this->sheetIndex = $sheetIndex;
}
/**
* Get the middleware the job should be dispatched through.
*
* @return array
*/
public function middleware()
{
return (method_exists($this->sheetExport, 'middleware')) ? $this->sheetExport->middleware() : [];
}
/**
* @param Writer $writer
*
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
public function handle(Writer $writer)
{
(new LocalizeJob($this->sheetExport))->handle($this, function () use ($writer) {
$writer = $writer->reopen($this->temporaryFile, $this->writerType);
$sheet = $writer->getSheetByIndex($this->sheetIndex);
$sheet->fromView($this->sheetExport, $this->sheetIndex);
$writer->write($this->sheetExport, $this->temporaryFile, $this->writerType);
});
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/ReadChunk.php | src/Jobs/ReadChunk.php | <?php
namespace Maatwebsite\Excel\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Cache;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterChunk;
use Maatwebsite\Excel\Events\ImportFailed;
use Maatwebsite\Excel\Files\RemoteTemporaryFile;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Filters\ChunkReadFilter;
use Maatwebsite\Excel\HasEventBus;
use Maatwebsite\Excel\Imports\HeadingRowExtractor;
use Maatwebsite\Excel\Sheet;
use Maatwebsite\Excel\Transactions\TransactionHandler;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Reader\IReader;
use Throwable;
class ReadChunk implements ShouldQueue
{
use Queueable, HasEventBus, InteractsWithQueue;
/**
* @var int
*/
public $timeout;
/**
* @var int
*/
public $tries;
/**
* @var int
*/
public $maxExceptions;
/**
* @var int
*/
public $backoff;
/**
* @var string
*/
public $queue;
/**
* @var string
*/
public $connection;
/**
* @var WithChunkReading
*/
private $import;
/**
* @var IReader
*/
private $reader;
/**
* @var TemporaryFile
*/
private $temporaryFile;
/**
* @var string
*/
private $sheetName;
/**
* @var object
*/
private $sheetImport;
/**
* @var int
*/
private $startRow;
/**
* @var int
*/
private $chunkSize;
/**
* @var string
*/
private $uniqueId;
/**
* @param WithChunkReading $import
* @param IReader $reader
* @param TemporaryFile $temporaryFile
* @param string $sheetName
* @param object $sheetImport
* @param int $startRow
* @param int $chunkSize
*/
public function __construct(WithChunkReading $import, IReader $reader, TemporaryFile $temporaryFile, string $sheetName, $sheetImport, int $startRow, int $chunkSize)
{
$this->import = $import;
$this->reader = $reader;
$this->temporaryFile = $temporaryFile;
$this->sheetName = $sheetName;
$this->sheetImport = $sheetImport;
$this->startRow = $startRow;
$this->chunkSize = $chunkSize;
$this->timeout = $import->timeout ?? null;
$this->tries = $import->tries ?? null;
$this->maxExceptions = $import->maxExceptions ?? null;
$this->backoff = method_exists($import, 'backoff') ? $import->backoff() : ($import->backoff ?? null);
$this->connection = property_exists($import, 'connection') ? $import->connection : null;
$this->queue = property_exists($import, 'queue') ? $import->queue : null;
}
public function getUniqueId(): string
{
if (!isset($this->uniqueId)) {
$this->uniqueId = uniqid();
Cache::set('laravel-excel/read-chunk/' . $this->uniqueId, true);
}
return $this->uniqueId;
}
public static function isComplete(string $id): bool
{
return !Cache::has('laravel-excel/read-chunk/' . $id);
}
/**
* Get the middleware the job should be dispatched through.
*
* @return array
*/
public function middleware()
{
return (method_exists($this->import, 'middleware')) ? $this->import->middleware() : [];
}
/**
* Determine the time at which the job should timeout.
*
* @return \DateTime
*/
public function retryUntil()
{
return (method_exists($this->import, 'retryUntil')) ? $this->import->retryUntil() : null;
}
/**
* @param TransactionHandler $transaction
*
* @throws \Maatwebsite\Excel\Exceptions\SheetNotFoundException
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
public function handle(TransactionHandler $transaction)
{
if (method_exists($this->import, 'setChunkOffset')) {
$this->import->setChunkOffset($this->startRow);
}
if (method_exists($this->sheetImport, 'setChunkOffset')) {
$this->sheetImport->setChunkOffset($this->startRow);
}
if ($this->sheetImport instanceof WithCustomValueBinder) {
Cell::setValueBinder($this->sheetImport);
}
$headingRow = HeadingRowExtractor::headingRow($this->sheetImport);
$filter = new ChunkReadFilter(
$headingRow,
$this->startRow,
$this->chunkSize,
$this->sheetName
);
$this->reader->setReadFilter($filter);
$this->reader->setReadDataOnly(config('excel.imports.read_only', true));
$this->reader->setReadEmptyCells(!config('excel.imports.ignore_empty', false));
$spreadsheet = $this->reader->load(
$this->temporaryFile->sync()->getLocalPath()
);
$sheet = Sheet::byName(
$spreadsheet,
$this->sheetName
);
if ($sheet->getHighestRow() < $this->startRow) {
$sheet->disconnect();
$this->cleanUpTempFile();
return;
}
$transaction(function () use ($sheet) {
$sheet->import(
$this->sheetImport,
$this->startRow
);
$sheet->disconnect();
$this->cleanUpTempFile();
$sheet->raise(new AfterChunk($sheet, $this->import, $this->startRow));
});
}
/**
* @param Throwable $e
*/
public function failed(Throwable $e)
{
$this->cleanUpTempFile(true);
if ($this->import instanceof WithEvents) {
$this->registerListeners($this->import->registerEvents());
$this->raise(new ImportFailed($e));
if (method_exists($this->import, 'failed')) {
$this->import->failed($e);
}
}
}
private function cleanUpTempFile(bool $force = false): bool
{
if (!empty($this->uniqueId)) {
Cache::delete('laravel-excel/read-chunk/' . $this->uniqueId);
}
if (!$force && !config('excel.temporary_files.force_resync_remote')) {
return true;
}
if (!$this->temporaryFile instanceof RemoteTemporaryFile) {
return true;
}
return $this->temporaryFile->deleteLocalCopy();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Jobs/Middleware/LocalizeJob.php | src/Jobs/Middleware/LocalizeJob.php | <?php
namespace Maatwebsite\Excel\Jobs\Middleware;
use Closure;
use Illuminate\Contracts\Translation\HasLocalePreference;
use Illuminate\Support\Traits\Localizable;
class LocalizeJob
{
use Localizable;
/**
* @var object
*/
private $localizable;
/**
* LocalizeJob constructor.
*
* @param object $localizable
*/
public function __construct($localizable)
{
$this->localizable = $localizable;
}
/**
* Handles the job.
*
* @param mixed $job
* @param Closure $next
* @return mixed
*/
public function handle($job, Closure $next)
{
$locale = value(function () {
if ($this->localizable instanceof HasLocalePreference) {
return $this->localizable->preferredLocale();
}
return null;
});
return $this->withLocale($locale, function () use ($next, $job) {
return $next($job);
});
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Exceptions/ConcernConflictException.php | src/Exceptions/ConcernConflictException.php | <?php
namespace Maatwebsite\Excel\Exceptions;
use LogicException;
class ConcernConflictException extends LogicException implements LaravelExcelException
{
/**
* @return ConcernConflictException
*/
public static function queryOrCollectionAndView()
{
return new static('Cannot use FromQuery, FromArray or FromCollection and FromView on the same sheet.');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Exceptions/RowSkippedException.php | src/Exceptions/RowSkippedException.php | <?php
namespace Maatwebsite\Excel\Exceptions;
use Exception;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Validators\Failure;
class RowSkippedException extends Exception
{
/**
* @var Failure[]
*/
private $failures;
/**
* @param Failure ...$failures
*/
public function __construct(Failure ...$failures)
{
$this->failures = $failures;
parent::__construct();
}
/**
* @return Failure[]|Collection
*/
public function failures(): Collection
{
return new Collection($this->failures);
}
/**
* @return int[]
*/
public function skippedRows(): array
{
return $this->failures()->map->row()->all();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Exceptions/NoFilenameGivenException.php | src/Exceptions/NoFilenameGivenException.php | <?php
namespace Maatwebsite\Excel\Exceptions;
use InvalidArgumentException;
use Throwable;
class NoFilenameGivenException extends InvalidArgumentException implements LaravelExcelException
{
/**
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct(
$message = 'A filename needs to be passed in order to download the export',
$code = 0,
?Throwable $previous = null
) {
parent::__construct($message, $code, $previous);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Exceptions/UnreadableFileException.php | src/Exceptions/UnreadableFileException.php | <?php
namespace Maatwebsite\Excel\Exceptions;
use Exception;
use Throwable;
class UnreadableFileException extends Exception implements LaravelExcelException
{
/**
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct(
$message = 'File could not be read',
$code = 0,
?Throwable $previous = null
) {
parent::__construct($message, $code, $previous);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Exceptions/SheetNotFoundException.php | src/Exceptions/SheetNotFoundException.php | <?php
namespace Maatwebsite\Excel\Exceptions;
class SheetNotFoundException extends \Exception implements LaravelExcelException
{
/**
* @param string $name
* @return SheetNotFoundException
*/
public static function byName(string $name): SheetNotFoundException
{
return new static("Your requested sheet name [{$name}] is out of bounds.");
}
/**
* @param int $index
* @param int $sheetCount
* @return SheetNotFoundException
*/
public static function byIndex(int $index, int $sheetCount): SheetNotFoundException
{
return new static("Your requested sheet index: {$index} is out of bounds. The actual number of sheets is {$sheetCount}.");
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Exceptions/NoFilePathGivenException.php | src/Exceptions/NoFilePathGivenException.php | <?php
namespace Maatwebsite\Excel\Exceptions;
use InvalidArgumentException;
use Throwable;
class NoFilePathGivenException extends InvalidArgumentException implements LaravelExcelException
{
/**
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct(
$message = 'A filepath needs to be passed.',
$code = 0,
?Throwable $previous = null
) {
parent::__construct($message, $code, $previous);
}
/**
* @return NoFilePathGivenException
*/
public static function import()
{
return new static('A filepath or UploadedFile needs to be passed to start the import.');
}
/**
* @return NoFilePathGivenException
*/
public static function export()
{
return new static('A filepath needs to be passed in order to store the export.');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Exceptions/NoTypeDetectedException.php | src/Exceptions/NoTypeDetectedException.php | <?php
namespace Maatwebsite\Excel\Exceptions;
use Exception;
use Throwable;
class NoTypeDetectedException extends Exception implements LaravelExcelException
{
/**
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct(
$message = 'No ReaderType or WriterType could be detected. Make sure you either pass a valid extension to the filename or pass an explicit type.',
$code = 0,
?Throwable $previous = null
) {
parent::__construct($message, $code, $previous);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Exceptions/NoSheetsFoundException.php | src/Exceptions/NoSheetsFoundException.php | <?php
namespace Maatwebsite\Excel\Exceptions;
use LogicException;
class NoSheetsFoundException extends LogicException implements LaravelExcelException
{
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Exceptions/LaravelExcelException.php | src/Exceptions/LaravelExcelException.php | <?php
namespace Maatwebsite\Excel\Exceptions;
use Throwable;
interface LaravelExcelException extends Throwable
{
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Helpers/ArrayHelper.php | src/Helpers/ArrayHelper.php | <?php
namespace Maatwebsite\Excel\Helpers;
class ArrayHelper
{
/**
* @param array $array
* @return array
*/
public static function ensureMultipleRows(array $array): array
{
if (static::hasMultipleRows($array)) {
return $array;
}
return [$array];
}
/**
* Only have multiple rows, if each
* element in the array is an array itself.
*
* @param array $array
* @return bool
*/
public static function hasMultipleRows(array $array): bool
{
return count($array) === count(array_filter($array, 'is_array'));
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Helpers/FileTypeDetector.php | src/Helpers/FileTypeDetector.php | <?php
namespace Maatwebsite\Excel\Helpers;
use Maatwebsite\Excel\Exceptions\NoTypeDetectedException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class FileTypeDetector
{
/**
* @param $filePath
* @param string|null $type
* @return string|null
*
* @throws NoTypeDetectedException
*/
public static function detect($filePath, ?string $type = null)
{
if (null !== $type) {
return $type;
}
if (!$filePath instanceof UploadedFile) {
$pathInfo = pathinfo($filePath);
$extension = $pathInfo['extension'] ?? '';
} else {
$extension = $filePath->getClientOriginalExtension();
}
if (null === $type && trim($extension) === '') {
throw new NoTypeDetectedException();
}
return config('excel.extension_detector.' . strtolower($extension));
}
/**
* @param string $filePath
* @param string|null $type
* @return string
*
* @throws NoTypeDetectedException
*/
public static function detectStrict(string $filePath, ?string $type = null): string
{
$type = static::detect($filePath, $type);
if (!$type) {
throw new NoTypeDetectedException();
}
return $type;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Helpers/CellHelper.php | src/Helpers/CellHelper.php | <?php
namespace Maatwebsite\Excel\Helpers;
class CellHelper
{
/**
* @param string $coordinate
* @return string
*/
public static function getColumnFromCoordinate(string $coordinate): string
{
return preg_replace('/[0-9]/', '', $coordinate);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Imports/HeadingRowFormatter.php | src/Imports/HeadingRowFormatter.php | <?php
namespace Maatwebsite\Excel\Imports;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use InvalidArgumentException;
class HeadingRowFormatter
{
/**
* @const string
*/
const FORMATTER_NONE = 'none';
/**
* @const string
*/
const FORMATTER_SLUG = 'slug';
/**
* @var string
*/
protected static $formatter;
/**
* @var callable[]
*/
protected static $customFormatters = [];
/**
* @var array
*/
protected static $defaultFormatters = [
self::FORMATTER_NONE,
self::FORMATTER_SLUG,
];
/**
* @param array $headings
* @return array
*/
public static function format(array $headings): array
{
return (new Collection($headings))->map(function ($value, $key) {
return static::callFormatter($value, $key);
})->toArray();
}
/**
* @param string $name
*/
public static function default(?string $name = null)
{
if (null !== $name && !isset(static::$customFormatters[$name]) && !in_array($name, static::$defaultFormatters, true)) {
throw new InvalidArgumentException(sprintf('Formatter "%s" does not exist', $name));
}
static::$formatter = $name;
}
/**
* @param string $name
* @param callable $formatter
*/
public static function extend(string $name, callable $formatter)
{
static::$customFormatters[$name] = $formatter;
}
/**
* Reset the formatter.
*/
public static function reset()
{
static::default();
}
/**
* @param mixed $value
* @return mixed
*/
protected static function callFormatter($value, $key=null)
{
static::$formatter = static::$formatter ?? config('excel.imports.heading_row.formatter', self::FORMATTER_SLUG);
// Call custom formatter
if (isset(static::$customFormatters[static::$formatter])) {
$formatter = static::$customFormatters[static::$formatter];
return $formatter($value, $key);
}
if (empty($value)) {
return $key;
}
if (static::$formatter === self::FORMATTER_SLUG) {
return Str::slug($value, '_');
}
// No formatter (FORMATTER_NONE)
return $value;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Imports/EndRowFinder.php | src/Imports/EndRowFinder.php | <?php
namespace Maatwebsite\Excel\Imports;
use Maatwebsite\Excel\Concerns\WithLimit;
class EndRowFinder
{
/**
* @param object|WithLimit $import
* @param int $startRow
* @param int|null $highestRow
* @return int|null
*/
public static function find($import, ?int $startRow = null, ?int $highestRow = null)
{
if (!$import instanceof WithLimit) {
return null;
}
$limit = $import->limit();
if ($limit > $highestRow) {
return null;
}
// When no start row given,
// use the first row as start row.
$startRow = $startRow ?? 1;
// Subtract 1 row from the start row, so a limit
// of 1 row, will have the same start and end row.
return ($startRow - 1) + $limit;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Imports/HeadingRowExtractor.php | src/Imports/HeadingRowExtractor.php | <?php
namespace Maatwebsite\Excel\Imports;
use Maatwebsite\Excel\Concerns\WithColumnLimit;
use Maatwebsite\Excel\Concerns\WithGroupedHeadingRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Row;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class HeadingRowExtractor
{
/**
* @const int
*/
const DEFAULT_HEADING_ROW = 1;
/**
* @param WithHeadingRow|mixed $importable
* @return int
*/
public static function headingRow($importable): int
{
return method_exists($importable, 'headingRow')
? $importable->headingRow()
: self::DEFAULT_HEADING_ROW;
}
/**
* @param WithHeadingRow|mixed $importable
* @return int
*/
public static function determineStartRow($importable): int
{
if ($importable instanceof WithStartRow) {
return $importable->startRow();
}
// The start row is the row after the heading row if we have one!
return $importable instanceof WithHeadingRow
? self::headingRow($importable) + 1
: self::DEFAULT_HEADING_ROW;
}
/**
* @param Worksheet $worksheet
* @param WithHeadingRow|mixed $importable
* @return array
*/
public static function extract(Worksheet $worksheet, $importable): array
{
if (!$importable instanceof WithHeadingRow) {
return [];
}
$headingRowNumber = self::headingRow($importable);
$rows = iterator_to_array($worksheet->getRowIterator($headingRowNumber, $headingRowNumber));
$headingRow = head($rows);
$endColumn = $importable instanceof WithColumnLimit ? $importable->endColumn() : null;
return HeadingRowFormatter::format((new Row($headingRow))->toArray(null, false, false, $endColumn));
}
/**
* @param array $headingRow
* @param WithGroupedHeadingRow|mixed $importable
* @return array
*/
public static function extractGrouping($headingRow, $importable)
{
$headerIsGrouped = array_fill(0, count($headingRow), false);
if (!$importable instanceof WithGroupedHeadingRow) {
return $headerIsGrouped;
}
array_walk($headerIsGrouped, function (&$value, $key) use ($headingRow) {
if (array_count_values($headingRow)[$headingRow[$key]] > 1) {
$value = true;
}
});
return $headerIsGrouped;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Imports/ModelManager.php | src/Imports/ModelManager.php | <?php
namespace Maatwebsite\Excel\Imports;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\PersistRelations;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithSkipDuplicates;
use Maatwebsite\Excel\Concerns\WithUpsertColumns;
use Maatwebsite\Excel\Concerns\WithUpserts;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Exceptions\RowSkippedException;
use Maatwebsite\Excel\Imports\Persistence\CascadePersistManager;
use Maatwebsite\Excel\Validators\RowValidator;
use Maatwebsite\Excel\Validators\ValidationException;
use Throwable;
class ModelManager
{
/**
* @var array
*/
private $rows = [];
/**
* @var RowValidator
*/
private $validator;
/**
* @var bool
*/
private $remembersRowNumber = false;
/**
* @var CascadePersistManager
*/
private $cascade;
/**
* @param RowValidator $validator
*/
public function __construct(RowValidator $validator, CascadePersistManager $cascade)
{
$this->validator = $validator;
$this->cascade = $cascade;
}
/**
* @param int $row
* @param array $attributes
*/
public function add(int $row, array $attributes)
{
$this->rows[$row] = $attributes;
}
/**
* @param bool $remembersRowNumber
*/
public function setRemembersRowNumber(bool $remembersRowNumber)
{
$this->remembersRowNumber = $remembersRowNumber;
}
/**
* @param ToModel $import
* @param bool $massInsert
*
* @throws ValidationException
*/
public function flush(ToModel $import, bool $massInsert = false)
{
if ($import instanceof WithValidation) {
$this->validateRows($import);
}
if ($massInsert) {
$this->massFlush($import);
} else {
$this->singleFlush($import);
}
$this->rows = [];
}
/**
* @param ToModel $import
* @param array $attributes
* @param int|null $rowNumber
* @return Model[]|Collection
*/
public function toModels(ToModel $import, array $attributes, $rowNumber = null): Collection
{
if ($this->remembersRowNumber) {
$import->rememberRowNumber($rowNumber);
}
return Collection::wrap($import->model($attributes));
}
/**
* @param ToModel $import
*/
private function massFlush(ToModel $import)
{
$this->rows()
->flatMap(function (array $attributes, $index) use ($import) {
return $this->toModels($import, $attributes, $index);
})
->mapToGroups(function ($model) {
return [\get_class($model) => $this->prepare($model)->getAttributes()];
})
->each(function (Collection $models, string $model) use ($import) {
try {
/* @var Model $model */
if ($import instanceof WithUpserts) {
$model::query()->upsert(
$models->toArray(),
$import->uniqueBy(),
$import instanceof WithUpsertColumns ? $import->upsertColumns() : null
);
return;
} elseif ($import instanceof WithSkipDuplicates) {
$model::query()->insertOrIgnore($models->toArray());
return;
}
$model::query()->insert($models->toArray());
} catch (Throwable $e) {
$this->handleException($import, $e);
}
});
}
/**
* @param ToModel $import
*/
private function singleFlush(ToModel $import)
{
$this
->rows()
->each(function (array $attributes, $index) use ($import) {
$this->toModels($import, $attributes, $index)->each(function (Model $model) use ($import) {
try {
if ($import instanceof WithUpserts) {
$model->upsert(
$model->getAttributes(),
$import->uniqueBy(),
$import instanceof WithUpsertColumns ? $import->upsertColumns() : null
);
return;
} elseif ($import instanceof WithSkipDuplicates) {
$model::query()->insertOrIgnore([$model->getAttributes()]);
return;
}
if ($import instanceof PersistRelations) {
$this->cascade->persist($model);
} else {
$model->saveOrFail();
}
} catch (Throwable $e) {
$this->handleException($import, $e);
}
});
});
}
/**
* @param Model $model
* @return Model
*/
private function prepare(Model $model): Model
{
if ($model->usesTimestamps()) {
$time = $model->freshTimestamp();
$updatedAtColumn = $model->getUpdatedAtColumn();
// If model has updated at column and not manually provided.
if ($updatedAtColumn && null === $model->{$updatedAtColumn}) {
$model->setUpdatedAt($time);
}
$createdAtColumn = $model->getCreatedAtColumn();
// If model has created at column and not manually provided.
if ($createdAtColumn && null === $model->{$createdAtColumn}) {
$model->setCreatedAt($time);
}
}
return $model;
}
/**
* @param WithValidation $import
*
* @throws ValidationException
*/
private function validateRows(WithValidation $import)
{
try {
$this->validator->validate($this->rows, $import);
} catch (RowSkippedException $e) {
foreach ($e->skippedRows() as $row) {
unset($this->rows[$row]);
}
}
}
/**
* @return Collection
*/
private function rows(): Collection
{
return new Collection($this->rows);
}
private function handleException(ToModel $import, Throwable $e): void
{
if (!$import instanceof SkipsOnError) {
throw $e;
}
$import->onError($e);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Imports/ModelImporter.php | src/Imports/ModelImporter.php | <?php
namespace Maatwebsite\Excel\Imports;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
use Maatwebsite\Excel\Concerns\WithColumnLimit;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithFormatData;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithProgressBar;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Events\AfterBatch;
use Maatwebsite\Excel\HasEventBus;
use Maatwebsite\Excel\Row;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class ModelImporter
{
use HasEventBus;
/**
* @var ModelManager
*/
private $manager;
/**
* @param ModelManager $manager
*/
public function __construct(ModelManager $manager)
{
$this->manager = $manager;
}
/**
* @param Worksheet $worksheet
* @param ToModel $import
* @param int|null $startRow
* @param string|null $endColumn
*
* @throws \Maatwebsite\Excel\Validators\ValidationException
*/
public function import(Worksheet $worksheet, ToModel $import, int $startRow = 1)
{
if ($startRow > $worksheet->getHighestRow()) {
return;
}
if ($import instanceof WithEvents) {
$this->registerListeners($import->registerEvents());
}
$headingRow = HeadingRowExtractor::extract($worksheet, $import);
$headerIsGrouped = HeadingRowExtractor::extractGrouping($headingRow, $import);
$batchSize = $import instanceof WithBatchInserts ? $import->batchSize() : 1;
$endRow = EndRowFinder::find($import, $startRow, $worksheet->getHighestRow());
$progessBar = $import instanceof WithProgressBar;
$withMapping = $import instanceof WithMapping;
$withCalcFormulas = $import instanceof WithCalculatedFormulas;
$formatData = $import instanceof WithFormatData;
$withValidation = $import instanceof WithValidation && method_exists($import, 'prepareForValidation');
$endColumn = $import instanceof WithColumnLimit ? $import->endColumn() : null;
$this->manager->setRemembersRowNumber(method_exists($import, 'rememberRowNumber'));
$i = 0;
$batchStartRow = $startRow;
foreach ($worksheet->getRowIterator($startRow, $endRow) as $spreadSheetRow) {
$i++;
$row = new Row($spreadSheetRow, $headingRow, $headerIsGrouped);
if (!$import instanceof SkipsEmptyRows || !$row->isEmpty($withCalcFormulas)) {
$rowArray = $row->toArray(null, $withCalcFormulas, $formatData, $endColumn);
if ($import instanceof SkipsEmptyRows && method_exists($import, 'isEmptyWhen') && $import->isEmptyWhen($rowArray)) {
continue;
}
if ($withValidation) {
$rowArray = $import->prepareForValidation($rowArray, $row->getIndex());
}
if ($withMapping) {
$rowArray = $import->map($rowArray);
}
$this->manager->add(
$row->getIndex(),
$rowArray
);
// Flush each batch.
if (($i % $batchSize) === 0) {
$this->flush($import, $batchSize, $batchStartRow);
$batchStartRow += $i;
$i = 0;
if ($progessBar) {
$import->getConsoleOutput()->progressAdvance($batchSize);
}
}
}
}
if ($i > 0) {
// Flush left-overs.
$this->flush($import, $batchSize, $batchStartRow);
}
}
private function flush(ToModel $import, int $batchSize, int $startRow)
{
$this->manager->flush($import, $batchSize > 1);
$this->raise(new AfterBatch($this->manager, $import, $batchSize, $startRow));
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Imports/Persistence/CascadePersistManager.php | src/Imports/Persistence/CascadePersistManager.php | <?php
namespace Maatwebsite\Excel\Imports\Persistence;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Transactions\TransactionHandler;
/** @todo */
class CascadePersistManager
{
/**
* @var TransactionHandler
*/
private $transaction;
/**
* @param TransactionHandler $transaction
*/
public function __construct(TransactionHandler $transaction)
{
$this->transaction = $transaction;
}
/**
* @param Model $model
* @return bool
*/
public function persist(Model $model): bool
{
return ($this->transaction)(function () use ($model) {
return $this->save($model);
});
}
/**
* @param Model $model
* @return bool
*/
private function save(Model $model): bool
{
if (!$model->save()) {
return false;
}
foreach ($model->getRelations() as $relationName => $models) {
$models = array_filter(
$models instanceof Collection ? $models->all() : [$models]
);
$relation = $model->{$relationName}();
if ($relation instanceof BelongsTo) {
if (!$this->persistBelongsTo($relation, $models)) {
return false;
}
}
if ($relation instanceof BelongsToMany) {
if (!$this->persistBelongsToMany($relation, $models)) {
return false;
}
}
}
// We need to save the model again to
// make sure all updates are performed.
$model->save();
return true;
}
/**
* @param BelongsTo $relation
* @param array $models
* @return bool
*/
private function persistBelongsTo(BelongsTo $relation, array $models): bool
{
// With belongs to, we first need to save all relations,
// so we can use their foreign key to attach to the relation.
foreach ($models as $model) {
// Cascade any relations that this child model may have.
if (!$this->save($model)) {
return false;
}
$relation->associate($model);
}
return true;
}
/**
* @param BelongsToMany $relation
* @param array $models
* @return bool
*/
private function persistBelongsToMany(BelongsToMany $relation, array $models): bool
{
foreach ($models as $model) {
$relation->save($model);
// Cascade any relations that this child model may have.
if (!$this->save($model)) {
return false;
}
}
return true;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Fakes/ExcelFake.php | src/Fakes/ExcelFake.php | <?php
namespace Maatwebsite\Excel\Fakes;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\PendingDispatch;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Traits\Macroable;
use Maatwebsite\Excel\Exporter;
use Maatwebsite\Excel\Importer;
use Maatwebsite\Excel\Reader;
use PHPUnit\Framework\Assert;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class ExcelFake implements Exporter, Importer
{
use Macroable;
/**
* @var array
*/
protected $downloads = [];
/**
* @var array
*/
protected $stored = [];
/**
* @var array
*/
protected $queued = [];
/**
* @var array
*/
protected $raws = [];
/**
* @var array
*/
protected $imported = [];
/**
* @var bool
*/
protected $matchByRegex = false;
/**
* @var object|null
*/
protected $job;
/**
* {@inheritdoc}
*/
public function download($export, string $fileName, ?string $writerType = null, array $headers = [])
{
$this->downloads[$fileName] = $export;
return new BinaryFileResponse(__DIR__ . '/fake_file');
}
/**
* {@inheritdoc}
*
* @param string|null $diskName Fallback for usage with named properties
*/
public function store($export, string $filePath, ?string $disk = null, ?string $writerType = null, $diskOptions = [], ?string $diskName = null)
{
if ($export instanceof ShouldQueue) {
return $this->queue($export, $filePath, $disk ?: $diskName, $writerType);
}
$this->stored[$disk ?: $diskName ?: 'default'][$filePath] = $export;
return true;
}
/**
* {@inheritdoc}
*/
public function queue($export, string $filePath, ?string $disk = null, ?string $writerType = null, $diskOptions = [])
{
Queue::fake();
$this->stored[$disk ?? 'default'][$filePath] = $export;
$this->queued[$disk ?? 'default'][$filePath] = $export;
$this->job = new class
{
use Queueable;
public function handle()
{
//
}
};
Queue::push($this->job);
return new PendingDispatch($this->job);
}
/**
* @param object $export
* @param string $writerType
* @return string
*/
public function raw($export, string $writerType)
{
$this->raws[get_class($export)] = $export;
return 'RAW-CONTENTS';
}
/**
* @param object $import
* @param string|UploadedFile $file
* @param string|null $disk
* @param string|null $readerType
* @return Reader|PendingDispatch
*/
public function import($import, $file, ?string $disk = null, ?string $readerType = null)
{
if ($import instanceof ShouldQueue) {
return $this->queueImport($import, $file, $disk, $readerType);
}
$filePath = ($file instanceof UploadedFile) ? $file->getClientOriginalName() : $file;
$this->imported[$disk ?? 'default'][$filePath] = $import;
return $this;
}
/**
* @param object $import
* @param string|UploadedFile $file
* @param string|null $disk
* @param string|null $readerType
* @return array
*/
public function toArray($import, $file, ?string $disk = null, ?string $readerType = null): array
{
$filePath = ($file instanceof UploadedFile) ? $file->getFilename() : $file;
$this->imported[$disk ?? 'default'][$filePath] = $import;
return [];
}
/**
* @param object $import
* @param string|UploadedFile $file
* @param string|null $disk
* @param string|null $readerType
* @return Collection
*/
public function toCollection($import, $file, ?string $disk = null, ?string $readerType = null): Collection
{
$filePath = ($file instanceof UploadedFile) ? $file->getFilename() : $file;
$this->imported[$disk ?? 'default'][$filePath] = $import;
return new Collection();
}
/**
* @param ShouldQueue $import
* @param string|UploadedFile $file
* @param string|null $disk
* @param string $readerType
* @return PendingDispatch
*/
public function queueImport(ShouldQueue $import, $file, ?string $disk = null, ?string $readerType = null)
{
Queue::fake();
$filePath = ($file instanceof UploadedFile) ? $file->getFilename() : $file;
$this->queued[$disk ?? 'default'][$filePath] = $import;
$this->imported[$disk ?? 'default'][$filePath] = $import;
$this->job = new class
{
use Queueable;
public function handle()
{
//
}
};
Queue::push($this->job);
return new PendingDispatch($this->job);
}
/**
* When asserting downloaded, stored, queued or imported, use regular expression
* to look for a matching file path.
*
* @return void
*/
public function matchByRegex()
{
$this->matchByRegex = true;
}
/**
* When asserting downloaded, stored, queued or imported, use regular string
* comparison for matching file path.
*
* @return void
*/
public function doNotMatchByRegex()
{
$this->matchByRegex = false;
}
/**
* @param string $fileName
* @param callable|null $callback
*/
public function assertDownloaded(string $fileName, $callback = null)
{
$fileName = $this->assertArrayHasKey($fileName, $this->downloads, sprintf('%s is not downloaded', $fileName));
$callback = $callback ?: function () {
return true;
};
Assert::assertTrue(
$callback($this->downloads[$fileName]),
"The file [{$fileName}] was not downloaded with the expected data."
);
}
/**
* @param string $filePath
* @param string|callable|null $disk
* @param callable|null $callback
*/
public function assertStored(string $filePath, $disk = null, $callback = null)
{
if (is_callable($disk)) {
$callback = $disk;
$disk = null;
}
$disk = $disk ?? 'default';
$storedOnDisk = $this->stored[$disk] ?? [];
$filePath = $this->assertArrayHasKey(
$filePath,
$storedOnDisk,
sprintf('%s is not stored on disk %s', $filePath, $disk)
);
$callback = $callback ?: function () {
return true;
};
Assert::assertTrue(
$callback($storedOnDisk[$filePath]),
"The file [{$filePath}] was not stored with the expected data."
);
}
/**
* @param string $filePath
* @param string|callable|null $disk
* @param callable|null $callback
*/
public function assertQueued(string $filePath, $disk = null, $callback = null)
{
if (is_callable($disk)) {
$callback = $disk;
$disk = null;
}
$disk = $disk ?? 'default';
$queuedForDisk = $this->queued[$disk] ?? [];
$filePath = $this->assertArrayHasKey(
$filePath,
$queuedForDisk,
sprintf('%s is not queued for export on disk %s', $filePath, $disk)
);
$callback = $callback ?: function () {
return true;
};
Assert::assertTrue(
$callback($queuedForDisk[$filePath]),
"The file [{$filePath}] was not stored with the expected data."
);
}
public function assertQueuedWithChain($chain): void
{
Queue::assertPushedWithChain(get_class($this->job), $chain);
}
/**
* @param string $classname
* @param callable|null $callback
*/
public function assertExportedInRaw(string $classname, $callback = null)
{
Assert::assertArrayHasKey($classname, $this->raws, sprintf('%s is not exported in raw', $classname));
$callback = $callback ?: function () {
return true;
};
Assert::assertTrue(
$callback($this->raws[$classname]),
"The [{$classname}] export was not exported in raw with the expected data."
);
}
/**
* @param string $filePath
* @param string|callable|null $disk
* @param callable|null $callback
*/
public function assertImported(string $filePath, $disk = null, $callback = null)
{
if (is_callable($disk)) {
$callback = $disk;
$disk = null;
}
$disk = $disk ?? 'default';
$importedOnDisk = $this->imported[$disk] ?? [];
$filePath = $this->assertArrayHasKey(
$filePath,
$importedOnDisk,
sprintf('%s is not stored on disk %s', $filePath, $disk)
);
$callback = $callback ?: function () {
return true;
};
Assert::assertTrue(
$callback($importedOnDisk[$filePath]),
"The file [{$filePath}] was not imported with the expected data."
);
}
/**
* Asserts that an array has a specified key and returns the key if successful.
*
* @see matchByRegex for more information about file path matching
*
* @param string $key
* @param array $array
* @param string $message
* @return string
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws Exception
*/
protected function assertArrayHasKey(string $key, array $disk, string $message = ''): string
{
if ($this->matchByRegex) {
$files = array_keys($disk);
$results = preg_grep($key, $files);
Assert::assertGreaterThan(0, count($results), $message);
Assert::assertEquals(1, count($results), "More than one result matches the file name expression '$key'.");
return array_values($results)[0];
}
Assert::assertArrayHasKey($key, $disk, $message);
return $key;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Mixins/StoreCollectionMixin.php | src/Mixins/StoreCollectionMixin.php | <?php
namespace Maatwebsite\Excel\Mixins;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class StoreCollectionMixin
{
/**
* @return callable
*/
public function storeExcel()
{
return function (string $filePath, ?string $disk = null, ?string $writerType = null, $withHeadings = false) {
$export = new class($this, $withHeadings) implements FromCollection, WithHeadings
{
use Exportable;
/**
* @var bool
*/
private $withHeadings;
/**
* @var Collection
*/
private $collection;
/**
* @param Collection $collection
* @param bool $withHeadings
*/
public function __construct(Collection $collection, bool $withHeadings = false)
{
$this->collection = $collection->toBase();
$this->withHeadings = $withHeadings;
}
/**
* @return Collection
*/
public function collection()
{
return $this->collection;
}
/**
* @return array
*/
public function headings(): array
{
if (!$this->withHeadings) {
return [];
}
return is_array($first = $this->collection->first())
? $this->collection->collapse()->keys()->all()
: array_keys($first->toArray());
}
};
return $export->store($filePath, $disk, $writerType);
};
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Mixins/ImportMacro.php | src/Mixins/ImportMacro.php | <?php
namespace Maatwebsite\Excel\Mixins;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ImportMacro
{
public function __invoke()
{
return function (string $filename, ?string $disk = null, ?string $readerType = null) {
$import = new class(get_class($this->getModel())) implements ToModel, WithHeadingRow
{
use Importable;
/**
* @var string
*/
private $model;
/**
* @param string $model
*/
public function __construct(string $model)
{
$this->model = $model;
}
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
return (new $this->model)->fill($row);
}
};
return $import->import($filename, $disk, $readerType);
};
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Mixins/StoreQueryMacro.php | src/Mixins/StoreQueryMacro.php | <?php
namespace Maatwebsite\Excel\Mixins;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Sheet;
class StoreQueryMacro
{
public function __invoke()
{
return function (string $filePath, ?string $disk = null, ?string $writerType = null, $withHeadings = false) {
$export = new class($this, $withHeadings) implements FromQuery, WithHeadings
{
use Exportable;
/**
* @var bool
*/
private $withHeadings;
/**
* @var Builder
*/
private $query;
/**
* @param $query
* @param bool $withHeadings
*/
public function __construct($query, bool $withHeadings = false)
{
$this->query = $query;
$this->withHeadings = $withHeadings;
}
/**
* @return Builder
*/
public function query()
{
return $this->query;
}
/**
* @return array
*/
public function headings(): array
{
if (!$this->withHeadings) {
return [];
}
$firstRow = (clone $this->query)->first();
if ($firstRow) {
return array_keys(Sheet::mapArraybleRow($firstRow));
}
return [];
}
};
return $export->store($filePath, $disk, $writerType);
};
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Mixins/DownloadCollectionMixin.php | src/Mixins/DownloadCollectionMixin.php | <?php
namespace Maatwebsite\Excel\Mixins;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Sheet;
class DownloadCollectionMixin
{
/**
* @return callable
*/
public function downloadExcel()
{
return function (string $fileName, ?string $writerType = null, $withHeadings = false, array $responseHeaders = []) {
$export = new class($this, $withHeadings) implements FromCollection, WithHeadings
{
use Exportable;
/**
* @var bool
*/
private $withHeadings;
/**
* @var Collection
*/
private $collection;
/**
* @param Collection $collection
* @param bool $withHeading
*/
public function __construct(Collection $collection, bool $withHeading = false)
{
$this->collection = $collection->toBase();
$this->withHeadings = $withHeading;
}
/**
* @return Collection
*/
public function collection()
{
return $this->collection;
}
/**
* @return array
*/
public function headings(): array
{
if (!$this->withHeadings) {
return [];
}
$firstRow = $this->collection->first();
if ($firstRow instanceof Arrayable || \is_object($firstRow)) {
return array_keys(Sheet::mapArraybleRow($firstRow));
}
return $this->collection->collapse()->keys()->all();
}
};
return $export->download($fileName, $writerType, $responseHeaders);
};
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Mixins/DownloadQueryMacro.php | src/Mixins/DownloadQueryMacro.php | <?php
namespace Maatwebsite\Excel\Mixins;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Sheet;
class DownloadQueryMacro
{
public function __invoke()
{
return function (string $fileName, ?string $writerType = null, $withHeadings = false) {
$export = new class($this, $withHeadings) implements FromQuery, WithHeadings
{
use Exportable;
/**
* @var bool
*/
private $withHeadings;
/**
* @var Builder
*/
private $query;
/**
* @param $query
* @param bool $withHeadings
*/
public function __construct($query, bool $withHeadings = false)
{
$this->query = $query;
$this->withHeadings = $withHeadings;
}
/**
* @return Builder
*/
public function query()
{
return $this->query;
}
/**
* @return array
*/
public function headings(): array
{
if (!$this->withHeadings) {
return [];
}
$firstRow = (clone $this->query)->first();
if ($firstRow) {
return array_keys(Sheet::mapArraybleRow($firstRow));
}
return [];
}
};
return $export->download($fileName, $writerType);
};
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Mixins/ImportAsMacro.php | src/Mixins/ImportAsMacro.php | <?php
namespace Maatwebsite\Excel\Mixins;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
class ImportAsMacro
{
public function __invoke()
{
return function (string $filename, callable $mapping, ?string $disk = null, ?string $readerType = null) {
$import = new class(get_class($this->getModel()), $mapping) implements ToModel
{
use Importable;
/**
* @var string
*/
private $model;
/**
* @var callable
*/
private $mapping;
/**
* @param string $model
* @param callable $mapping
*/
public function __construct(string $model, callable $mapping)
{
$this->model = $model;
$this->mapping = $mapping;
}
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
return (new $this->model)->fill(
($this->mapping)($row)
);
}
};
return $import->import($filename, $disk, $readerType);
};
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Transactions/TransactionHandler.php | src/Transactions/TransactionHandler.php | <?php
namespace Maatwebsite\Excel\Transactions;
interface TransactionHandler
{
/**
* @param callable $callback
* @return mixed
*/
public function __invoke(callable $callback);
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/src/Transactions/DbTransactionHandler.php | src/Transactions/DbTransactionHandler.php | <?php
namespace Maatwebsite\Excel\Transactions;
use Illuminate\Database\ConnectionInterface;
class DbTransactionHandler implements TransactionHandler
{
/**
* @var ConnectionInterface
*/
private $connection;
/**
* @param ConnectionInterface $connection
*/
public function __construct(ConnectionInterface $connection)
{
$this->connection = $connection;
}
/**
* @param callable $callback
* @return mixed
*
* @throws \Throwable
*/
public function __invoke(callable $callback)
{
return $this->connection->transaction($callback);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.