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 |
|---|---|---|---|---|---|---|---|---|
pktharindu/nova-permissions | https://github.com/pktharindu/nova-permissions/blob/6f4fcb125558d41304440cd3029944a0a840df19/src/Nova/Role.php | src/Nova/Role.php | <?php
namespace Pktharindu\NovaPermissions\Nova;
use Laravel\Nova\Fields\Slug;
use Laravel\Nova\Http\Requests\NovaRequest;
use Laravel\Nova\Resource;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\BelongsToMany;
use Pktharindu\NovaPermissions\Checkboxes;
use Pktharindu\NovaPermissions\Role as RoleModel;
class Role extends Resource
{
public static $model = RoleModel::class;
public static function group()
{
return __(config('nova-permissions.role_resource_group', 'Other'));
}
public static $title = 'name';
public static $search = [
'id',
'slug',
'name',
];
public static $with = [
'users',
];
public function actions(NovaRequest $request)
{
return [];
}
public function cards(NovaRequest $request)
{
return [];
}
public function fields(NovaRequest $request)
{
return [
ID::make()->sortable(),
Text::make(__('Name'), 'name')
->rules('required')
->sortable(),
Slug::make(__('Slug'), 'slug')
->from('name')
->rules('required')
->creationRules('unique:' . config('nova-permissions.table_names.roles', 'roles'))
->updateRules('unique:' . config('nova-permissions.table_names.roles', 'roles') . ',slug,{{resourceId}}')
->sortable()
->hideFromIndex(),
Checkboxes::make(__('Permissions'), 'permissions')
->withGroups()
->options(collect(config('nova-permissions.permissions'))->map(function ($permission, $key) {
return [
'group' => __($permission['group']),
'option' => $key,
'label' => __($permission['display_name']),
'description' => __($permission['description']),
];
})->groupBy('group')->toArray()),
Text::make(__('Users'), function () {
return \count($this->users);
})->onlyOnIndex(),
BelongsToMany::make(__('Users'), 'users', config('nova-permissions.user_resource', 'App\Nova\User'))
->searchable(),
];
}
public function filters(NovaRequest $request)
{
return [];
}
public static function label()
{
return __('Roles');
}
public function lenses(NovaRequest $request)
{
return [];
}
public static function singularLabel()
{
return __('Role');
}
}
| php | MIT | 6f4fcb125558d41304440cd3029944a0a840df19 | 2026-01-05T05:01:00.821895Z | false |
pktharindu/nova-permissions | https://github.com/pktharindu/nova-permissions/blob/6f4fcb125558d41304440cd3029944a0a840df19/src/Providers/AuthServiceProvider.php | src/Providers/AuthServiceProvider.php | <?php
namespace Pktharindu\NovaPermissions\Providers;
use Illuminate\Support\Facades\Gate;
use Pktharindu\NovaPermissions\Traits\ValidatesPermissions;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
use ValidatesPermissions;
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [];
/**
* Register any authentication / authorization services.
*/
public function boot()
{
$this->registerPolicies();
$this->defineGates();
}
private function defineGates()
{
foreach (config('nova-permissions.permissions') as $key => $permissions) {
Gate::define($key, function (User $user) use ($key) {
if ($this->nobodyHasAccess($key)) {
return true;
}
return $user->hasPermissionTo($key);
});
}
}
}
| php | MIT | 6f4fcb125558d41304440cd3029944a0a840df19 | 2026-01-05T05:01:00.821895Z | false |
pktharindu/nova-permissions | https://github.com/pktharindu/nova-permissions/blob/6f4fcb125558d41304440cd3029944a0a840df19/src/Policies/Policy.php | src/Policies/Policy.php | <?php
namespace Pktharindu\NovaPermissions\Policies;
use Illuminate\Support\Facades\Gate;
class Policy
{
/**
* Retrieves all registered policies from the Gate. Only policies registered in the application
* can be assigned to groups.
*
* @return array
*/
public static function all()
{
return array_keys(Gate::abilities());
}
}
| php | MIT | 6f4fcb125558d41304440cd3029944a0a840df19 | 2026-01-05T05:01:00.821895Z | false |
pktharindu/nova-permissions | https://github.com/pktharindu/nova-permissions/blob/6f4fcb125558d41304440cd3029944a0a840df19/config/nova-permissions.php | config/nova-permissions.php | <?php
return [
/*
|--------------------------------------------------------------------------
| User model class
|--------------------------------------------------------------------------
*/
'user_model' => 'App\Models\User',
/*
|--------------------------------------------------------------------------
| Nova User resource tool class
|--------------------------------------------------------------------------
*/
'user_resource' => 'App\Nova\User',
/*
|--------------------------------------------------------------------------
| The group associated with the resource
|--------------------------------------------------------------------------
*/
'role_resource_group' => 'Other',
/*
|--------------------------------------------------------------------------
| Database table names
|--------------------------------------------------------------------------
| When using the "HasRoles" trait from this package, we need to know which
| table should be used to retrieve your roles. We have chosen a basic
| default value but you may easily change it to any table you like.
*/
'table_names' => [
'roles' => 'roles',
'role_permission' => 'role_permission',
'role_user' => 'role_user',
'users' => 'users',
],
/*
|--------------------------------------------------------------------------
| Application Permissions
|--------------------------------------------------------------------------
*/
'permissions' => [
'view users' => [
'display_name' => 'View users',
'description' => 'Can view users',
'group' => 'User',
],
'create users' => [
'display_name' => 'Create users',
'description' => 'Can create users',
'group' => 'User',
],
'edit users' => [
'display_name' => 'Edit users',
'description' => 'Can edit users',
'group' => 'User',
],
'delete users' => [
'display_name' => 'Delete users',
'description' => 'Can delete users',
'group' => 'User',
],
'view roles' => [
'display_name' => 'View roles',
'description' => 'Can view roles',
'group' => 'Role',
],
'create roles' => [
'display_name' => 'Create roles',
'description' => 'Can create roles',
'group' => 'Role',
],
'edit roles' => [
'display_name' => 'Edit roles',
'description' => 'Can edit roles',
'group' => 'Role',
],
'delete roles' => [
'display_name' => 'Delete roles',
'description' => 'Can delete roles',
'group' => 'Role',
],
],
];
| php | MIT | 6f4fcb125558d41304440cd3029944a0a840df19 | 2026-01-05T05:01:00.821895Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/src/Model/Behavior/ImagineBehavior.php | src/Model/Behavior/ImagineBehavior.php | <?php
/**
* Copyright 2011-2016, Florian Krämer
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* Copyright 2011-2016, Florian Krämer
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Burzum\Imagine\Model\Behavior;
use Burzum\Imagine\Lib\ImagineUtility;
use Cake\ORM\Behavior;
use Cake\ORM\Table;
use Imagine\Image\AbstractImage;
/**
* CakePHP Imagine Plugin
*/
class ImagineBehavior extends Behavior {
/**
* Default settings array
*
* @var array
*/
protected $_defaultConfig = [
'engine' => 'Gd',
'processorClass' => '\Burzum\Imagine\Lib\ImageProcessor'
];
/**
* Class name of the image processor to use.
*
* @var string
*/
protected $_processorClass;
/**
* Constructor
*
* @param Table $table The table this behavior is attached to.
* @param array $settings The settings for this behavior.
*/
public function __construct(Table $table, array $settings = []) {
parent::__construct($table, $settings);
$class = '\Imagine\\' . $this->config('engine') . '\Imagine';
$this->Imagine = new $class();
$this->_table = $table;
$processorClass = $this->config('processorClass');
$this->_processor = new $processorClass($this->config());
}
/**
* Returns the image processor object.
*
* @return mixed
*/
public function getImageProcessor() {
return $this->_processor;
}
/**
* Get the imagine object
*
* @deprecated Call ImagineBehavior->getImageProcessor()->imagine() instead.
* @return Imagine object
*/
public function imagineObject() {
return $this->_processor->imagine();
}
/**
* Delegate the calls to the image processor lib.
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __call($method, $args) {
if (method_exists($this->_processor, $args)) {
return call_user_func_array([$this->_processor, $method], $args);
}
}
/**
* Loads an image and applies operations on it.
*
* Caching and taking care of the file storage is NOT the purpose of this method!
*
* @param string|\Imagine\Image\AbstractImage $ImageObject
* @param string $output
* @param array $imagineOptions
* @param array $operations
* @throws \InvalidArgumentException
* @return bool
*/
public function processImage($image, $output = null, $imagineOptions = [], $operations = []) {
if (is_string($image)) {
$this->_processor->open($image);
$image = $this->_processor->image();
}
if (!$image instanceof AbstractImage) {
throw new \InvalidArgumentException('An instance of `\Imagine\Image\AbstractImage` is required, you passed `%s`!', get_class($image));
}
$event = $this->_table->dispatchEvent('ImagineBehavior.beforeApplyOperations', compact('image', 'operations'));
if ($event->isStopped()) {
return $event->result;
}
$data = $event->data();
$this->_applyOperations(
$data['operations'],
$data['image']
);
$event = $this->_table->dispatchEvent('ImagineBehavior.afterApplyOperations', $data);
if ($event->isStopped()) {
return $event->result;
}
if ($output === null) {
return $image;
}
return $this->_processor->save($output, $imagineOptions);
}
/**
* Applies the actual image operations to the image.
*
* @param array $operations
* @param array $image
* @throws \BadMethodCallException
* @return void
*/
protected function _applyOperations($operations, $image) {
foreach ($operations as $operation => $params) {
$event = $this->_table->dispatchEvent('ImagineBehavior.applyOperation', compact('image', 'operations'));
if ($event->isStopped()) {
continue;
}
if (method_exists($this->_table, $operation)) {
$this->_table->{$operation}($image, $params);
} elseif (method_exists($this->_processor, $operation)) {
$this->_processor->{$operation}($params);
} else {
throw new \BadMethodCallException(__d('imagine', 'Unsupported image operation `{0}`!', $operation));
}
}
}
/**
* Turns the operations and their params into a string that can be used in a file name to cache an image.
*
* Suffix your image with the string generated by this method to be able to batch delete a file that has versions of it cached.
* The intended usage of this is to store the files as my_horse.thumbnail+width-100-height+100.jpg for example.
*
* So after upload store your image meta data in a db, give the filename the id of the record and suffix it
* with this string and store the string also in the db. In the views, if no further control over the image access is needed,
* you can simply direct-link the image like $this->Html->image('/images/05/04/61/my_horse.thumbnail+width-100-height+100.jpg');
*
* @param array $operations Imagine image operations
* @param array $separators Optional
* @param bool $hash
* @return string Filename compatible String representation of the operations
* @link http://support.microsoft.com/kb/177506
*/
public function operationsToString($operations, $separators = [], $hash = false) {
return ImagineUtility::operationsToString($operations, $separators, $hash);
}
/**
* hashImageOperations
*
* @param array $imageSizes
* @param int $hashLength
* @return string
*/
public function hashImageOperations($imageSizes, $hashLength = 8) {
return ImagineUtility::hashImageOperations($imageSizes, $hashLength = 8);
}
public function getImageSize($Image) {
return $this->_processor->getImageSize($Image);
}
}
| php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/src/Controller/Component/ImagineComponent.php | src/Controller/Component/ImagineComponent.php | <?php
/**
* Copyright 2011-2016, Florian Krämer
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* Copyright 2011-2016, Florian Krämer
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Burzum\Imagine\Controller\Component;
use Cake\Controller\Component;
use Cake\Utility\Security;
use Cake\Controller\ComponentRegistry;
use Cake\Event\Event;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use InvalidArgumentException;
/**
* CakePHP Imagine Plugin
*
* @package Imagine.Controller.Component
*/
class ImagineComponent extends Component {
/**
* Default config
*
* These are merged with user-provided config when the component is used.
*
* @var array
*/
protected $_defaultConfig = [
'hashField' => 'hash',
'checkHash' => true,
'actions' => [],
];
/**
* Controller instance
*
* @var object
*/
public $Controller;
/**
* Image processing operations taken by ImagineBehavior::processImage()
*
* This property is auto populated by ImagineComponent::unpackParams()
*
* @var array
*/
public $operations = [];
/**
* Constructor
*
* @param \Cake\Controller\ComponentRegistry $collection
* @param array $config Config options array
*/
public function __construct(ComponentRegistry $collection, $config = []) {
parent::__construct($collection, $config);
$Controller = $collection->getController();
$this->request = $Controller->request;
$this->response = $Controller->response;
}
/**
* Start Up
*
* @param Event $Event
* @return void
*/
public function startup(Event $Event) {
$Controller = $Event->subject();
$this->Controller = $Controller;
if (!empty($this->_config['actions'])) {
if (in_array($this->Controlle->action, $this->_config['actions'])) {
if ($this->_config['checkHash'] === true) {
$this->checkHash();
}
$this->unpackParams();
}
}
}
/**
* Creates a hash based on the named params but ignores the hash field
*
* The hash can also be used to determine if there is already a cached version
* of the requested image that was processed with these params. How you do that
* is up to you.
*
* @throws InvalidArgumentException
* @return mixed String if a hash could be retrieved, false if not
*/
public function getHash() {
$mediaSalt = Configure::read('Imagine.salt');
if (empty($mediaSalt)) {
throw new InvalidArgumentException('Please configure Imagine.salt using Configure::write(\'Imagine.salt\', \'YOUR-SALT-VALUE\')');
}
if (!empty($this->request->query)) {
$params = $this->request->query;
unset($params[$this->_config['hashField']]);
ksort($params);
return Security::hash(serialize($params) . $mediaSalt);
}
return false;
}
/**
* Compares the hash passed within the named args with the hash calculated based
* on the other named args and the imagine salt
*
* This is done to avoid that people can randomly generate tons of images by
* just incrementing the width and height for example in the url.
*
* @param bool $error If set to false no 404 page will be rendered if the hash is wrong
* @throws NotFoundException if the hash was not present
* @return bool True if the hashes match
*/
public function checkHash($error = true) {
if (!isset($this->request->query[$this->_config['hashField']]) && $error) {
throw new NotFoundException();
}
$result = $this->request->query[$this->_config['hashField']] == $this->getHash();
if (!$result && $error) {
throw new NotFoundException();
}
return $result;
}
/**
* Unpacks the strings into arrays that were packed with ImagineHelper::pack()
*
* @param array $namedParams
* @internal param array $params If empty the method tries to get them from Controller->request['named']
* @return array Array with operation options for imagine, if none found an empty array
*/
public function unpackParams($namedParams = []) {
if (empty($namedParams)) {
$namedParams = $this->request->query;
}
foreach ($namedParams as $name => $params) {
$tmpParams = explode(';', $params);
$resultParams = [];
foreach ($tmpParams as &$param) {
list($key, $value) = explode('|', $param);
$resultParams[$key] = $value;
}
$resultParams;
$namedParams[$name] = $resultParams;
}
$this->operations = $namedParams;
return $namedParams;
}
}
| php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/src/Lib/ImagineUtility.php | src/Lib/ImagineUtility.php | <?php
/**
* Copyright 2011-2016, Florian Krämer
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* Copyright 2011-2016, Florian Krämer
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Burzum\Imagine\Lib;
use Cake\Core\Configure;
class ImagineUtility {
/**
* Turns the operations and their params into a string that can be used in a file name to cache an image.
*
* Suffix your image with the string generated by this method to be able to batch delete a file that has versions of it cached.
* The intended usage of this is to store the files as my_horse.thumbnail+width-100-height+100.jpg for example.
*
* So after upload store your image meta data in a db, give the filename the id of the record and suffix it
* with this string and store the string also in the db. In the views, if no further control over the image access is needed,
* you can simply direct-link the image like $this->Html->image('/images/05/04/61/my_horse.thumbnail+width-100-height+100.jpg');
*
* @param array $operations
* @param array $separators
* @param mixed $hash
* @throws BadFunctionCallException
* @return string Filename compatible String representation of the operations
* @link http://support.microsoft.com/kb/177506
*/
public static function operationsToString($operations, $separators = [], $hash = false) {
ksort($operations);
$defaultSeparators = [
'operations' => '.',
'params' => '+',
'value' => '-'
];
$separators = array_merge($defaultSeparators, $separators);
$result = '';
foreach ($operations as $operation => $data) {
$tmp = [];
foreach ($data as $key => $value) {
if (is_string($value) || is_numeric($value)) {
$tmp[] = $key . $separators['value'] . $value;
}
}
$result = $separators['operations'] . $operation . $separators['params'] . implode($separators['params'], $tmp);
}
if ($hash && $result !== '') {
if (function_exists($hash)) {
return $hash($result);
}
throw new \BadFunctionCallException();
}
return $result;
}
/**
* This method expects an array of Model.configName => operationsArray
*
* @param array $imageSizes
* @param int $hashLength
* @return array Model.configName => hashValue
*/
public static function hashImageOperations($imageSizes, $hashLength = 8) {
foreach ($imageSizes as $model => $operations) {
foreach ($operations as $name => $operation) {
$imageSizes[$model][$name] = substr(self::operationsToString($operation, [], 'md5'), 0, $hashLength);
}
}
return $imageSizes;
}
/**
* Gets the orientation of an image file.
*
* @param string $imageFile Image file to get the orientation from.
* @return int The degree of orientation.
*/
public static function getImageOrientation($imageFile) {
if (!file_exists($imageFile)) {
throw new \RuntimeException(sprintf('File %s not found!', $imageFile));
}
$exif = exif_read_data($imageFile);
if ($exif === false) {
return false;
}
$angle = 0;
if (!empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 0:
$angle = 0;
break;
case 3:
$angle = 180;
break;
case 6:
$angle = -90;
break;
case 8:
$angle = 90;
break;
default:
$angle = 0;
break;
}
return $angle;
}
return $angle;
}
}
| php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/src/Lib/ImageProcessor.php | src/Lib/ImageProcessor.php | <?php
namespace Burzum\Imagine\Lib;
use Cake\Core\InstanceConfigTrait;
use Imagine\Image\ImageInterface;
use Imagine\Image\Point;
use Imagine\Image\Box;
class ImageProcessor {
use InstanceConfigTrait;
/**
* Default settings
*
* @var array
*/
protected $_defaultConfig = [
'engine' => 'Gd'
];
/**
* Imagine Engine Instance
*
* @var \Imagine\Image\AbstractImagine;
*/
protected $_imagine = null;
/**
* Image object instace
*
* @var \Imagine\Image\AbstractImage
*/
protected $_image = null;
/**
* Constructor
*
* @var array
*/
public function __construct(array $config = []) {
$this->config($config);
}
/**
* Get the imagine object
*
* @return Imagine object
*/
public function imagine($renew = false) {
if (empty($this->_imagine) || $renew === true) {
$class = '\Imagine\\' . $this->config('engine') . '\Imagine';
$this->_imagine = new $class();
return $this->_imagine;
}
return $this->_imagine;
}
/**
* Opens an image file for processing.
*
* @param string $image Image file.
* @return Object Imagine Image class object, depending on the chosen engine.
*/
public function open($image) {
if (!file_exists($image)) {
throw new \RuntimeException(sprintf('File `%s` does not exist!', $image));
}
$this->_image = $this->imagine()->open($image);
return $this;
}
/**
* Gets the image object.
*
* @return \Imagine\Image\AbstractImage;
*/
public function image() {
return $this->_image;
}
/**
* Loads an image and applies operations on it
*
* Caching and taking care of the file storage is NOT the purpose of this method!
*
* @param null $output
* @param array $imagineOptions
* @param array $operations
* @throws \BadMethodCallException
* @internal param string $image source image path
* @internal param $mixed
* @internal param \Imagine $array image objects save() 2nd parameter options
* @return bool
*/
public function batchProcess($output = null, $operations = [], $imagineOptions = []) {
foreach ($operations as $operation => $params) {
if (method_exists($this, $operation)) {
$this->{$operation}($params);
} else {
throw new \BadMethodCallException(sprintf('Unsupported image operation %s!', $operation));
}
}
if ($output === null) {
return $this->_image;
$this->_image = null;
}
return $this->save($output, $imagineOptions);
}
/**
* Saves an image.
*
* @param string $output Output filename.
* @param array $options Imagine image saving options.
* @return bool
*/
public function save($output, array $options = []) {
$this->_image->save($output, $options);
$this->_image = null;
return true;
}
/**
* Compatibility method for legacy reasons.
*
* @deprecated Use batchProcess() instead.
*/
public function processImage($output = null, $imagineOptions = [], $operations = []) {
user_error('processImage() is deprecated, use batchProcess() instead!', E_NOTICE);
return $this->batchProcess($output, $operations, $imagineOptions);
}
/**
* Turns the operations and their params into a string that can be used in a file name to cache an image.
*
* Suffix your image with the string generated by this method to be able to batch delete a file that has versions of it cached.
* The intended usage of this is to store the files as my_horse.thumbnail+width-100-height+100.jpg for example.
*
* So after upload store your image meta data in a db, give the filename the id of the record and suffix it
* with this string and store the string also in the db. In the views, if no further control over the image access is needd,
* you can simply direct linke the image like $this->Html->image('/images/05/04/61/my_horse.thumbnail+width-100-height+100.jpg');
*
* @param array $operations Imagine image operations
* @param array $separators Optional
* @param bool $hash
* @return string Filename compatible String representation of the operations
* @link http://support.microsoft.com/kb/177506
*/
public function operationsToString($operations, $separators = [], $hash = false) {
return ImagineUtility::operationsToString($operations, $separators, $hash);
}
/**
* hashImageOperations
*
* @param array $imageSizes
* @param int $hashLength
* @return string
*/
public function hashImageOperations($imageSizes, $hashLength = 8) {
return ImagineUtility::hashImageOperations($imageSizes, $hashLength = 8);
}
/**
* Wrapper for Imagines crop
*
* @param array Array of options for processing the image
* @throws \InvalidArgumentException
* @return $this
*/
public function crop(array $options = []) {
if (empty($options['height']) || empty($options['width'])) {
throw new \InvalidArgumentException('You have to pass height and width in the options!');
}
$defaults = [
'cropX' => 0,
'cropY' => 0
];
$options = array_merge($defaults, $options);
$this->_image->crop(
new Point($options['cropX'], $options['cropY']),
new Box($options['width'], $options['height'])
);
return $this;
}
/**
* Crops an image based on its widht or height, crops it to a square and resizes it to the given size
*
* @param array Array of options for processing the image.
* @throws \InvalidArgumentException
* @return $this
*/
public function squareCenterCrop(array $options = []) {
if (empty($options['size'])) {
throw new \InvalidArgumentException(__d('imagine', 'You have to pass size in the options!'));
}
$imageSize = $this->getImageSize($this->_image);
$width = $imageSize[0];
$height = $imageSize[1];
if ($width > $height) {
$x2 = $height;
$y2 = $height;
$x = ($width - $height) / 2;
$y = 0;
} else {
$x2 = $width;
$y2 = $width;
$x = 0;
$y = ($height - $width) / 2;
}
$this->_image->crop(new \Imagine\Image\Point($x, $y), new \Imagine\Image\Box($x2, $y2));
$this->_image->resize(new \Imagine\Image\Box($options['size'], $options['size']));
return $this;
}
/**
* Widen
*
* @param array Array of options for processing the image.
* @throws \InvalidArgumentException
* @return void
*/
public function widen(array $options = []) {
if (empty($options['size'])) {
throw new \InvalidArgumentException(__d('imagine', 'You must pass a size value!'));
}
$this->widenAndHeighten(['width' => $options['size']]);
return $this;
}
/**
* Heighten
*
* @param array Array of options for processing the image.
* @throws \InvalidArgumentException
* @return $this
*/
public function heighten(array $options = []) {
if (empty($options['size'])) {
throw new \InvalidArgumentException(__d('imagine', 'You must pass a size value!'));
}
$this->widenAndHeighten(['height' => $options['size']]);
}
/**
* WidenAndHeighten
*
* @param array Array of options for processing the image.
* @throws \InvalidArgumentException
* @return $this
*/
public function widenAndHeighten(array $options = []) {
if (empty($options['height']) && empty($options['width']) && empty($options['size'])) {
throw new \InvalidArgumentException(__d('imagine', 'You have to pass a height, width or size!'));
}
if (!empty($options['height']) && !empty($options['width'])) {
throw new \InvalidArgumentException(__d('imagine', 'You can only scale by width or height!'));
}
if (isset($options['width'])) {
$size = $options['width'];
$method = 'widen';
} elseif (isset($options['height'])) {
$size = $options['height'];
$method = 'heighten';
} else {
$size = $options['size'];
$method = 'scale';
}
$imageSize = $this->getImageSize($this->_image);
$width = $imageSize[0];
$height = $imageSize[1];
if (isset($options['noUpScale'])) {
if ($method === 'widen') {
if ($size > $width) {
throw new \InvalidArgumentException('You can not scale up!');
}
} elseif ('heighten') {
if ($size > $height) {
throw new \InvalidArgumentException('You can not scale up!');
}
}
}
if (isset($options['noDownScale'])) {
if ($method === 'widen') {
if ($size < $width) {
throw new \InvalidArgumentException('You can not scale down!');
}
} elseif ('heighten') {
if ($size < $height) {
throw new \InvalidArgumentException('You can not scale down!');
}
}
}
$Box = new Box($width, $height);
$Box = $Box->{$method}($size);
$this->_image->resize($Box);
return $this;
}
/**
* Heighten
*
* @param array $options
* @throws \InvalidArgumentException
* @return void
*/
public function scale(array $options = []) {
if (empty($options['factor'])) {
throw new \InvalidArgumentException(__d('imagine', 'You must pass a factor value!'));
}
$imageSize = $this->getImageSize();
$width = $imageSize[0];
$height = $imageSize[1];
$Box = new Box($width, $height);
$Box = $Box->scale($options['factor']);
$this->_image->resize($Box);
return $this;
}
/**
* Wrapper for Imagine flipHorizontally and flipVertically
*
* @param array Array of options for processing the image.
* @throws \InvalidArgumentException
* @return $this
*/
public function flip(array $options = []) {
if (!isset($options['direction'])) {
$options['direction'] = 'vertically';
}
if (!in_array($options['direction'], ['vertically', 'horizontally'])) {
throw new \InvalidArgumentException(__d('imagine', 'Invalid direction, use vertically or horizontally'));
}
$method = 'flip' . $options['direction'];
$this->_image->{$method}();
return $this;
}
/**
* Wrapper for rotate
*
* @param array Array of options for processing the image.
* @return $this
*/
public function rotate(array $options = []) {
$this->_image->rotate($options['degree']);
return $this;
}
/**
* Wrapper for Imagines thumbnail.
*
* This method had a bunch of issues and the code inside the method is a
* workaround! Please see:
*
* @link https://github.com/burzum/cakephp-imagine-plugin/issues/42
* @link https://github.com/avalanche123/Imagine/issues/478
*
* @throws \InvalidArgumentException
* @param array Array of options for processing the image.
* @throws InvalidArgumentException if no height or width was passed
* @return $this
*/
public function thumbnail(array $options = []) {
if (empty($options['height']) || empty($options['width'])) {
throw new \InvalidArgumentException(__d('imagine', 'You have to pass height and width in the options!'));
}
$mode = ImageInterface::THUMBNAIL_INSET;
if (isset($options['mode']) && $options['mode'] === 'outbound') {
$mode = ImageInterface::THUMBNAIL_OUTBOUND;
}
$filter = ImageInterface::FILTER_UNDEFINED;
if (isset($options['filter'])) {
$filter = $options['filter'];
}
$size = new Box($options['width'], $options['height']);
$imageSize = $this->_image->getSize();
$ratios = array(
$size->getWidth() / $imageSize->getWidth(),
$size->getHeight() / $imageSize->getHeight()
);
// if target width is larger than image width
// AND target height is longer than image height
if ($size->contains($imageSize)) {
return $this->_image;
}
if ($mode === ImageInterface::THUMBNAIL_INSET) {
$ratio = min($ratios);
} else {
$ratio = max($ratios);
}
if ($mode === ImageInterface::THUMBNAIL_OUTBOUND) {
if (!$imageSize->contains($size)) {
$size = new Box(
min($imageSize->getWidth(), $size->getWidth()),
min($imageSize->getHeight(), $size->getHeight())
);
} else {
$imageSize = $this->_image->getSize()->scale($ratio);
$this->_image->resize($imageSize, $filter);
}
$this->_image->crop(new Point(
max(0, round(($imageSize->getWidth() - $size->getWidth()) / 2)),
max(0, round(($imageSize->getHeight() - $size->getHeight()) / 2))
), $size);
} else {
if (!$imageSize->contains($size)) {
$imageSize = $imageSize->scale($ratio);
$this->_image->resize($imageSize, $filter);
} else {
$imageSize = $this->_image->getSize()->scale($ratio);
$this->_image->resize($imageSize, $filter);
}
}
return $this;
}
/**
* Wrapper for Imagines resize
*
* @param array Array of options for processing the image
* @throws \InvalidArgumentException
* @return $this
*/
public function resize(array $options = []) {
if (empty($options['height']) || empty($options['width'])) {
throw new \InvalidArgumentException(__d('imagine', 'You have to pass height and width in the options!'));
}
$this->_image->resize(new Box($options['width'], $options['height']));
return $this;
}
/**
* Gets the size of an image
*
* @param mixed Imagine Image object or string of a file name
* @return array first value is width, second height
* @see Imagine\Image\ImageInterface::getSize()
*/
public function getImageSize($Image = null) {
$Image = $this->_getImage($Image);
$BoxInterface = $Image->getSize($Image);
return [
$BoxInterface->getWidth(),
$BoxInterface->getHeight(),
'x' => $BoxInterface->getWidth(),
'y' => $BoxInterface->getHeight()
];
}
/**
* Gets an image from a file string or returns the image object that is
* loaded in the ImageProcessor::_image property.
*
* @param string|null $Image
* @return \Imagine\Image\
*/
protected function _getImage($Image = null) {
if (is_string($Image)) {
$class = 'Imagine\\' . $this->config('engine') . '\Imagine';
$Imagine = new $class();
return $Imagine->open($Image);
}
if (!empty($this->_image)) {
return $this->_image;
}
throw new \RuntimeException('Could not get the image object!');
}
}
| php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/src/View/Helper/ImagineHelper.php | src/View/Helper/ImagineHelper.php | <?php
/**
* Copyright 2011-2016, Florian Krämer
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* Copyright 2011-2016, Florian Krämer
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Burzum\Imagine\View\Helper;
use Cake\Core\Configure;
use Cake\View\Helper;
use Cake\Utility\Security;
use Cake\Routing\Router;
/**
* CakePHP Imagine Plugin
*
* @package Imagine.View.Helper
*/
class ImagineHelper extends Helper {
/**
* Finds URL for specified action and sign it.
*
* Returns an URL pointing to a combination of controller and action. Param
*
* @param mixed $url Cake-relative URL, like "/products/edit/92" or "/presidents/elect/4"
* or an array specifying any of the following: 'controller', 'action',
* and/or 'plugin', in addition to named arguments (keyed array elements),
* and standard URL arguments (indexed array elements)
* @param bool $full If true, the full base URL will be prepended to the result
* @param array $options List of named arguments that need to sign
* @return string Full translated signed URL with base path and with
*/
public function url($url = null, $full = false, $options = []) {
if (is_string($url)) {
$url = array_merge(['plugin' => 'media', 'admin' => false, 'controller' => 'media', 'action' => 'image'], [$url]);
}
// backward compatibility check, switches params 2 and 3
if (is_bool($options)) {
$tmp = $options;
$options = $full;
$full = $tmp;
}
$options = $this->pack($options);
$options['hash'] = $this->hash($options);
$url = array_merge((array)$url, $options + ['base' => false]);
return Router::url($url, $full);
}
/**
* Signs the url with a salted hash
*
* @throws \RuntimeException
* @param array $options
* @return string
*/
public function hash($options) {
$mediaSalt = Configure::read('Imagine.salt');
if (empty($mediaSalt)) {
throw new \RuntimeException(__d('imagine', 'Please configure {0} using {1}', 'Imagine.salt', 'Configure::write(\'Imagine.salt\', \'YOUR-SALT-VALUE\')'));
}
ksort($options);
return urlencode(Security::hash(serialize($options) . $mediaSalt));
}
/**
* Packs the image options array into an array of named arguments that can be used in a cake url
*
* @param array $options
* @return array
*/
public function pack($options) {
$result = [];
foreach ($options as $operation => $data) {
$tmp = [];
foreach ($data as $key => $value) {
if (is_string($value) || is_numeric($value)) {
$tmp[] = "$key|$value";
}
}
$result[$operation] = implode(';', $tmp);
}
return $result;
}
}
| php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/tests/bootstrap.php | tests/bootstrap.php | <?php
use Cake\Core\Plugin;
$findRoot = function ($root) {
do {
$lastRoot = $root;
$root = dirname($root);
if (is_dir($root . '/vendor/cakephp/cakephp')) {
return $root;
}
} while ($root !== $lastRoot);
throw new \Exception('Cannot find the root of the application, unable to run tests');
};
$root = $findRoot(__FILE__);
unset($findRoot);
chdir($root);
if (file_exists($root . '/config/bootstrap.php')) {
//require $root . '/config/bootstrap.php';
//return;
}
require $root . '/vendor/cakephp/cakephp/tests/bootstrap.php';
$loader = require $root . '/vendor/autoload.php';
$loader->setPsr4('Cake\\', './vendor/cakephp/cakephp/src');
$loader->setPsr4('Cake\Test\\', './vendor/cakephp/cakephp/tests');
Plugin::load('Burzum/Imagine', [
'path' => dirname(dirname(__FILE__)) . DS,
'autoload' => true,
'bootstrap' => false,
'routes' => false
]); | php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/tests/Fixture/ImageFixture.php | tests/Fixture/ImageFixture.php | <?php
/**
* Copyright 2011-2015, Florian Krämer
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* Copyright 2011-2015, Florian Krämer
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Burzum\Imagine\Test\Fixture;
use Cake\TestSuite\Fixture\TestFixture;
class ImageFixture extends TestFixture {
/**
* fields property
*
* @var array
*/
public $fields = [
'id' => ['type' => 'integer'],
'title' => ['type' => 'string', 'null' => false],
'_constraints' => [
'primary' => ['type' => 'primary', 'columns' => ['id']]
]
];
/**
* Records
*
* @var array
*/
public $records = [
['title' => 'First Image'],
['title' => 'Second Image']
];
}
| php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/tests/TestCase/Model/Behavior/ImagineBehaviorTest.php | tests/TestCase/Model/Behavior/ImagineBehaviorTest.php | <?php
/**
* Copyright 2011-2015, Florian Krämer
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
* Copyright 2011-2015, Florian Krämer
*
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Burzum\Imagine\Test\TestCase\Model\Behavior;
use Cake\TestSuite\TestCase;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Core\Plugin;
use Imagine\Filter\Transformation;
class ImagineTestModel extends Table {
public $name = 'ImagineTestModel';
}
class ImagineBehaviorTest extends TestCase {
/**
* Holds the instance of the model
*
* @var mixed
*/
public $Article = null;
/**
* Fixtures
*
* @var array
*/
public $fixtures = [
'plugin.Burzum\Imagine.Image'
];
/**
* setUp
*
* @return void
*/
public function setUp() {
$this->Model = TableRegistry::get('ImagineTestModel');
$this->Model->addBehavior('Burzum/Imagine.Imagine');
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
unset($this->Model);
TableRegistry::clear();
}
/**
* testImagineObject
*
* @return void
*/
public function testImagineObject() {
$result = $this->Model->imagineObject();
$this->assertTrue(is_a($result, 'Imagine\Gd\Imagine'));
}
/**
* testParamsAsFileString
*
* @return void
*/
public function testOperationsToString() {
$operations = [
'thumbnail' => [
'width' => 200,
'height' => 150
]
];
$result = $this->Model->operationsToString($operations);
$this->assertEquals($result, '.thumbnail+width-200+height-150');
}
/**
* getImageSize
*
* @return void
*/
public function getImageSize() {
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'cake.icon.png';
$result = $this->Model->getImageSize($image);
$this->assertEquals($result, [20, 20]);
}
/**
* testCropInvalidArgumentException
*
* @expectedException \InvalidArgumentException
* @return void
*/
public function testCropInvalidArgumentException() {
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'titus.jpg';
$this->Model->processImage($image, TMP . 'crop.jpg', [], [
'crop' => []
]);
}
/**
* testCrop
*
* @return void
*/
public function testResize() {
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'titus.jpg';
$this->Model->processImage($image, TMP . 'resize.jpg', [], [
'resize' => [
'height' => 150,
'width' => 200
]
]);
$result = $this->Model->getImageSize(TMP . 'resize.jpg');
$this->assertEquals($result, [200, 150, 'x' => 200, 'y' => 150]);
}
/**
* testCrop
*
* @return void
*/
public function testCrop() {
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'titus.jpg';
$this->Model->processImage($image, TMP . 'crop.jpg', [], [
'crop' => [
'height' => 300,
'width' => 300
]
]);
$result = $this->Model->getImageSize(TMP . 'crop.jpg');
$this->assertEquals($result, [300, 300, 'x' => 300, 'y' => 300]);
}
/**
* testThumbnail
*
* @return void
*/
public function testThumbnail() {
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'titus.jpg';
$this->Model->processImage($image, TMP . 'thumbnailInbound.jpg', [], [
'thumbnail' => [
'mode' => 'inbound',
'height' => 300,
'width' => 300
]
]);
$result = $this->Model->getImageSize(TMP . 'thumbnailInbound.jpg');
$this->assertEquals($result, [226, 300, 'x' => 226, 'y' => 300]);
$this->Model->processImage($image, TMP . 'thumbnailOutbound.jpg', [], [
'thumbnail' => [
'mode' => 'outbound',
'height' => 300,
'width' => 300
]
]);
$result = $this->Model->getImageSize(TMP . 'thumbnailOutbound.jpg');
$this->assertEquals($result, [300, 300, 'x' => 300, 'y' => 300]);
$this->Model->processImage($image, TMP . 'thumbnail2.jpg', [], [
'thumbnail' => [
'mode' => 'inset',
'height' => 300,
'width' => 300
]
]
);
$result = $this->Model->getImageSize(TMP . 'thumbnail2.jpg');
$this->assertEquals($result, [226, 300, 'x' => 226, 'y' => 300]);
}
/**
* testSquareCenterCrop
*
* @return void
*/
public function testSquareCenterCrop() {
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'titus.jpg';
$this->Model->processImage($image, TMP . 'testSquareCenterCrop.jpg', [], [
'squareCenterCrop' => [
'size' => 255
]
]);
$result = $this->Model->getImageSize(TMP . 'testSquareCenterCrop.jpg');
$this->assertEquals($result, [255, 255, 'x' => 255, 'y' => 255]);
}
/**
* testgetImageSize
*
* @return void
*/
public function testGetImageSize() {
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'titus.jpg';
$result = $this->Model->getImageSize($image);
$this->assertEquals($result, [500, 664, 'x' => 500, 'y' => 664]);
}
/**
* testWidenAndHeighten
*
* @return void
*/
public function testWidenAndHeighten() {
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'titus.jpg';
$result = $this->Model->getImageSize($image);
$this->assertEquals($result, [500, 664, 'x' => 500, 'y' => 664]);
// Width
$this->Model->processImage($image, TMP . 'widen.jpg', [], [
'widen' => [
'size' => 200
]
]);
$result = $this->Model->getImageSize(TMP . 'widen.jpg');
$this->assertEquals($result, [200, 266, 'x' => 200, 'y' => 266]);
// Height
$this->Model->processImage($image, TMP . 'heighten.jpg', [], [
'heighten' => [
'size' => 200
]
]
);
$result = $this->Model->getImageSize(TMP . 'heighten.jpg');
$this->assertEquals($result, [151, 200, 'x' => 151, 'y' => 200]);
}
/**
* testScale
*
* @return void
*/
public function testScale() {
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'titus.jpg';
// Scale
$this->Model->processImage($image, TMP . 'scale-factor2.jpg', [], [
'scale' => [
'factor' => 2
]
]);
$result = $this->Model->getImageSize(TMP . 'scale-factor2.jpg');
$this->assertEquals($result, [1000, 1328, 'x' => 1000, 'y' => 1328]);
// Scale2
$this->Model->processImage($image, TMP . 'scale-factor1.25.jpg', [], [
'scale' => [
'factor' => 1.25
]
]);
$result = $this->Model->getImageSize(TMP . 'scale-factor1.25.jpg');
$this->assertEquals($result, [625, 830, 'x' => 625, 'y' => 830]);
}
}
| php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/tests/TestCase/Controller/Component/ImagineComponentTest.php | tests/TestCase/Controller/Component/ImagineComponentTest.php | <?php
/**
* Copyright 2011-2015, Florian Krämer
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* Copyright 2011-2015, Florian Krämer
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Burzum\Imagine\Test\TestCase\Controller\Component;
use Cake\TestSuite\TestCase;
use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Core\Configure;
use Cake\Network\Request;
use Cake\Network\Response;
class ImagineImagesTestController extends Controller {
/**
* @var string
*/
public $name = 'Images';
/**
* @var array
*/
public $uses = ['Images'];
/**
* @var array
*/
public $components = [
'Burzum/Imagine.Imagine'
];
/**
* Redirect url
* @var mixed
*/
public $redirectUrl = null;
/**
*
*/
public function beforeFilter(Event $Event) {
parent::beforeFilter($Event);
$this->Imagine->userModel = 'UserModel';
}
/**
*
*/
public function redirect($url, $status = NULL, $exit = true) {
$this->redirectUrl = $url;
}
}
/**
* Imagine Component Test
*
* @package Imagine
* @subpackage Imagine.tests.cases.components
*/
class ImagineComponentTest extends TestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = [
'plugin.Burzum\Imagine.Image'
];
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
Configure::write('Imagine.salt', 'this-is-a-nice-salt');
$request = new Request();
$response = new Response();
$this->Controller = new ImagineImagesTestController($request, $response);
$this->Controller->Imagine->Controller = $this->Controller;
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Controller);
}
/**
* testGetHash method
*
* @return void
*/
public function testGetHash() {
$this->Controller->request->query = [
'thumbnail' => 'width|200;height|150'
];
$hash = $this->Controller->Imagine->getHash();
$this->assertTrue(is_string($hash));
}
/**
* testCheckHash method
*
* @return void
*/
public function testCheckHash() {
$this->Controller->request->query = [
'thumbnail' => 'width|200;height|150',
'hash' => '69aa9f46cdc5a200dc7539fc10eec00f2ba89023'
];
$this->Controller->Imagine->checkHash();
}
/**
* @expectedException Cake\Network\Exception\NotFoundException
*/
public function testInvalidHash() {
$this->Controller->request->query = [
'thumbnail' => 'width|200;height|150',
'hash' => 'wrong-hash-value'
];
$this->Controller->Imagine->checkHash();
}
/**
* @expectedException Cake\Network\Exception\NotFoundException
*/
public function testMissingHash() {
$this->Controller->request->query = [
'thumbnail' => 'width|200;height|150'
];
$this->Controller->Imagine->checkHash();
}
/**
* testCheckHash method
*
* @return void
*/
public function testUnpackParams() {
$this->assertEquals($this->Controller->Imagine->operations, []);
$this->Controller->request->query['thumbnail'] = 'width|200;height|150';
$this->Controller->Imagine->unpackParams();
$this->assertEquals($this->Controller->Imagine->operations, [
'thumbnail' => [
'width' => 200,
'height' => 150
]
]
);
}
}
| php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/tests/TestCase/Lib/ImagineUtilityTest.php | tests/TestCase/Lib/ImagineUtilityTest.php | <?php
/**
* Copyright 2011-2015, Florian Krämer
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* Copyright 2011-2015, Florian Krämer
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Burzum\Imagine\Test\TestCase\Lib;
use Burzum\Imagine\Lib\ImageProcessor;
use Cake\Core\Plugin;
use Cake\TestSuite\TestCase;
use Burzum\Imagine\Lib\ImagineUtility;
class ImagineUtilityTest extends TestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = [];
/**
* testOperationsToString
*
* @return void
*/
public function testOperationsToString() {
$operations = [
'thumbnail' => [
'width' => 200,
'height' => 150
]
];
$result = ImagineUtility::operationsToString($operations);
$this->assertEquals($result, '.thumbnail+width-200+height-150');
}
/**
* testHashImageOperations
*
* @return void
*/
public function testHashImageOperations() {
$operations = [
'SomeModel' => [
't200x150' => [
'thumbnail' => [
'width' => 200,
'height' => 150
]
]
]
];
$result = ImagineUtility::hashImageOperations($operations);
$this->assertEquals($result, [
'SomeModel' => ['t200x150' => '38b1868f']
]);
}
/**
* testGetImageOrientation
*
* @return void
*/
public function testGetImageOrientation() {
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'titus.jpg';
$result = ImagineUtility::getImageOrientation($image);
$this->assertEquals($result, 0);
$image = Plugin::path('Burzum/Imagine') . 'tests' . DS . 'Fixture' . DS . 'Portrait_6.jpg';
$result = ImagineUtility::getImageOrientation($image);
$this->assertEquals($result, -90);
try {
ImagineUtility::getImageOrientation('does-not-exist');
$this->fail('No \RuntimeException thrown as expected!');
} catch (\RuntimeException $e) {
}
}
}
| php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
burzum/cakephp-imagine-plugin | https://github.com/burzum/cakephp-imagine-plugin/blob/c88eaa490dcc60df0914536dbb5da32f78c45b1f/tests/TestCase/View/Helper/ImagineHelperTest.php | tests/TestCase/View/Helper/ImagineHelperTest.php | <?php
/**
* Copyright 2011-2015, Florian Krämer
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* Copyright 2011-2015, Florian Krämer
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Burzum\Imagine\Test\TestCase\View\Helper;
use Burzum\Imagine\View\Helper\ImagineHelper;
use Cake\TestSuite\TestCase;
use Cake\Core\Configure;
use Cake\View\View;
/**
* ImagineHelperTest class
*/
class ImagineHelperTest extends TestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
Configure::write('Imagine.salt', 'this-is-a-nice-salt');
$controller = null;
$View = new View($controller);
$this->Imagine = new ImagineHelper($View);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
unset($this->Imagine);
}
/**
* testUrl method
*
* @return void
*/
public function testUrl() {
$result = $this->Imagine->url(
[
'controller' => 'Images',
'action' => 'display',
1
],
false,
[
'thumbnail' => [
'width' => 200,
'height' => 150
]
]
);
$expected = '/Images/display/1?thumbnail=width%7C200%3Bheight%7C150&hash=69aa9f46cdc5a200dc7539fc10eec00f2ba89023';
$this->assertEquals($result, $expected);
}
/**
* testUrl method for backward compatibility
*
* @return void
*/
public function testUrlBackwardCompatibility() {
$param1 = [
'controller' => 'Images',
'action' => 'display',
1
];
$param2 = false;
$param3 = [
'thumbnail' => [
'width' => 200,
'height' => 150
]
];
$result1 = $this->Imagine->url($param1, $param2, $param3);
$result2 = $this->Imagine->url($param1, $param3, $param2);
$this->assertEquals($result1, $result2);
}
/**
* testHash method
*
* @return void
*/
public function testHash() {
$options = $this->Imagine->pack([
'thumbnail' => [
'width' => 200,
'height' => 150
]
]
);
$result = $this->Imagine->hash($options);
$this->assertEquals($result, '69aa9f46cdc5a200dc7539fc10eec00f2ba89023');
}
/**
* testHash method
*
* @expectedException Exception
* @return void
*/
public function testMissingSaltForHash() {
Configure::write('Imagine.salt', null);
$this->Imagine->hash('foo');
}
/**
* testUrl method
*
* @return void
*/
public function testPack() {
$result = $this->Imagine->pack([
'thumbnail' => [
'width' => 200,
'height' => 150
]
]
);
$this->assertEquals($result, ['thumbnail' => 'width|200;height|150']);
}
}
| php | MIT | c88eaa490dcc60df0914536dbb5da32f78c45b1f | 2026-01-05T05:01:08.087231Z | false |
Treblle/treblle-laravel | https://github.com/Treblle/treblle-laravel/blob/835166e5363913f2377b1e2ed992ce679035f8fd/src/TreblleServiceProvider.php | src/TreblleServiceProvider.php | <?php
declare(strict_types=1);
namespace Treblle\Laravel;
use function config;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Http\Kernel;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Foundation\Console\AboutCommand;
use Treblle\Laravel\Middlewares\TreblleMiddleware;
use Treblle\Laravel\Middlewares\TreblleEarlyMiddleware;
use Illuminate\Contracts\Container\BindingResolutionException;
/**
* Treblle Service Provider for Laravel.
*
* This service provider registers Treblle middleware, publishes configuration,
* integrates with Laravel Octane for accurate request timing, and provides
* integration with the Laravel `about` command.
*
* @package Treblle\Laravel
*/
final class TreblleServiceProvider extends ServiceProvider
{
/**
* The name of the SDK for identification in Treblle platform.
*/
public const SDK_NAME = 'laravel';
/**
* The current version of the Treblle Laravel SDK.
*/
public const SDK_VERSION = 6.0;
/**
* Bootstrap any application services.
*
* Registers middleware aliases, publishes configuration, sets up Laravel Octane
* integration for request timing, and adds Treblle information to the `about` command.
*
* @return void
* @throws BindingResolutionException
*/
public function boot(): void
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../config/treblle.php' => config_path('treblle.php'),
], 'treblle-config');
}
/** @var Router $router */
$router = $this->app->make(Router::class);
if (! isset($router->getMiddleware()['treblle'])) {
$router->aliasMiddleware('treblle', TreblleMiddleware::class);
}
if (! isset($router->getMiddleware()['treblle.early'])) {
$router->aliasMiddleware('treblle.early', TreblleEarlyMiddleware::class);
/** @var Kernel $kernel */
$kernel = $this->app->make(Kernel::class);
$kernel->prependToMiddlewarePriority(TreblleEarlyMiddleware::class);
}
/** @var Dispatcher $events */
$events = $this->app->make(Dispatcher::class);
$events->listen('Laravel\Octane\Events\RequestReceived', function ($event): void {
$event->request->attributes->set('treblle_request_started_at', microtime(true));
});
AboutCommand::add(
section: 'Treblle',
data: static fn (): array => [
'Version' => self::SDK_VERSION,
'URL' => config('treblle.url'),
'API Key' => config('treblle.api_key'),
'SDK Token' => config('treblle.sdk_token'),
'Ignored Environments' => config('treblle.ignored_environments'),
],
);
}
/**
* Register any application services.
*
* Merges the package configuration with the application's published configuration.
*
* @return void
*/
public function register(): void
{
$this->mergeConfigFrom(
path: __DIR__ . '/../config/treblle.php',
key: 'treblle',
);
}
}
| php | MIT | 835166e5363913f2377b1e2ed992ce679035f8fd | 2026-01-05T05:01:19.522984Z | false |
Treblle/treblle-laravel | https://github.com/Treblle/treblle-laravel/blob/835166e5363913f2377b1e2ed992ce679035f8fd/src/Jobs/SendTreblleData.php | src/Jobs/SendTreblleData.php | <?php
declare(strict_types=1);
namespace Treblle\Laravel\Jobs;
use Throwable;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Treblle\Laravel\DataTransferObject\TrebllePayloadData;
/**
* Queue job for sending Treblle monitoring data asynchronously.
*
* @package Treblle\Laravel\Jobs
*/
final class SendTreblleData implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public int $tries = 3;
/**
* The number of seconds to wait before retrying the job.
*
* @var int
*/
public int $backoff = 5;
/**
* The number of seconds the job can run before timing out.
*
* @var int
*/
public int $timeout = 10;
/**
* Create a new job instance.
*
* @param TrebllePayloadData $payloadData The pre-extracted Treblle payload data
*/
public function __construct(
private readonly TrebllePayloadData $payloadData
) {
}
/**
* Execute the job.
* @return void
*/
public function handle(): void
{
try {
// JSON encode and compress in one pass for better memory efficiency
$jsonPayload = json_encode($this->payloadData->toArray());
$compressedPayload = gzencode($jsonPayload, 6);
$url = $this->getBaseUrl();
// Log the payload being sent (only in debug mode)
if ($this->payloadData->debug) {
Log::info('Treblle: Sending payload', [
'url' => $url,
'api_key' => $this->payloadData->apiKey,
'sdk_token' => mb_substr($this->payloadData->sdkToken, 0, 10) . '...',
'payload_size' => mb_strlen($jsonPayload),
'compressed_size' => mb_strlen($compressedPayload),
'payload' => json_decode($jsonPayload, true), // Log as array for better readability
]);
}
// Use Laravel's HTTP client for better integration and testing
$response = Http::timeout(3)
->connectTimeout(3)
->withoutVerifying()
->withHeaders([
'Content-Type' => 'application/json',
'Content-Encoding' => 'gzip',
'x-api-key' => $this->payloadData->sdkToken,
'Accept-Encoding' => 'gzip',
])
->withBody($compressedPayload, 'application/json')
->post($url);
// Log the response (only in debug mode)
if ($this->payloadData->debug) {
Log::info('Treblle: Response received', [
'status_code' => $response->status(),
'headers' => $response->headers(),
'body' => $response->body(),
]);
}
} catch (Throwable $throwable) {
// Always log errors (important for troubleshooting)
Log::error('Treblle: Failed to send data', [
'error' => $throwable->getMessage(),
'trace' => $this->payloadData->debug ? $throwable->getTraceAsString() : null,
]);
if ($this->payloadData->debug) {
throw $throwable;
}
// Let Laravel's queue system handle retry logic
$this->fail($throwable);
}
}
/**
* Get the base URL for Treblle API.
*
* If a custom URL is provided, it will be used. Otherwise, a random
* endpoint from the available Treblle servers is selected for load
* balancing.
*
* @return string The Treblle API endpoint URL
*/
private function getBaseUrl(): string
{
$urls = [
'https://rocknrolla.treblle.com',
'https://punisher.treblle.com',
'https://sicario.treblle.com',
];
return $this->payloadData->url ?? $urls[array_rand($urls)];
}
}
| php | MIT | 835166e5363913f2377b1e2ed992ce679035f8fd | 2026-01-05T05:01:19.522984Z | false |
Treblle/treblle-laravel | https://github.com/Treblle/treblle-laravel/blob/835166e5363913f2377b1e2ed992ce679035f8fd/src/Exceptions/TreblleException.php | src/Exceptions/TreblleException.php | <?php
declare(strict_types=1);
namespace Treblle\Laravel\Exceptions;
use Exception;
/**
* Treblle Configuration Exception.
*
* Exception thrown when required Treblle configuration is missing or invalid.
* Provides specific factory methods for different configuration errors.
*
* @package Treblle\Laravel\Exceptions
*/
final class TreblleException extends Exception
{
/**
* Create an exception for missing SDK token configuration.
*
* The SDK token (previously called API key in v5.x) is required to authenticate
* with the Treblle API. This should be set in the TREBLLE_SDK_TOKEN environment
* variable.
*
* @return self A new exception instance with appropriate message
*/
public static function missingSdkToken(): self
{
return new TreblleException(
message: 'No SDK Token configured for Treblle. Ensure TREBLLE_SDK_TOKEN is set in your .env before trying again.',
);
}
/**
* Create an exception for missing API key configuration.
*
* The API key (previously called project ID in v5.x) identifies which
* Treblle project this request should be associated with. This should be
* set in the TREBLLE_API_KEY environment variable.
*
* @return self A new exception instance with appropriate message
*/
public static function missingApiKey(): self
{
return new TreblleException(
message: 'No API Key configured for Treblle. Ensure TREBLLE_API_KEY is set in your .env before trying again.',
);
}
}
| php | MIT | 835166e5363913f2377b1e2ed992ce679035f8fd | 2026-01-05T05:01:19.522984Z | false |
Treblle/treblle-laravel | https://github.com/Treblle/treblle-laravel/blob/835166e5363913f2377b1e2ed992ce679035f8fd/src/DataProviders/LaravelRequestDataProvider.php | src/DataProviders/LaravelRequestDataProvider.php | <?php
declare(strict_types=1);
namespace Treblle\Laravel\DataProviders;
use Throwable;
use Carbon\Carbon;
use Treblle\Php\Helpers\HeaderFilter;
use Treblle\Php\DataTransferObject\Request;
use Treblle\Php\Helpers\SensitiveDataMasker;
use Treblle\Php\Contract\RequestDataProvider;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
/**
* Laravel-specific Request Data Provider for Treblle.
*
* Implements the RequestDataProvider contract from treblle-php to extract
* and format request data from Laravel/Symfony request objects. Handles
* sensitive data masking, header filtering, and original payload capture.
*
* @package Treblle\Laravel\DataProviders
*/
final readonly class LaravelRequestDataProvider implements RequestDataProvider
{
/**
* Create a new Laravel request data provider instance.
*
* @param SensitiveDataMasker $fieldMasker Masker for sensitive data fields
* @param \Illuminate\Http\Request|SymfonyRequest $request The Laravel/Symfony request object
*/
public function __construct(
private SensitiveDataMasker $fieldMasker,
private \Illuminate\Http\Request|SymfonyRequest $request,
) {
}
/**
* Extract and format request data for Treblle.
*
* Builds a Request DTO containing all relevant request information including
* headers (filtered and masked), query parameters (masked), request body
* (masked), URL, IP address, user agent, HTTP method, and route path.
*
* @return Request The formatted request data transfer object
*/
public function getRequest(): Request
{
return new Request(
timestamp: Carbon::now('UTC')->format('Y-m-d H:i:s'),
url: $this->request->fullUrl(),
ip: $this->request->ip() ?? 'bogon',
user_agent: $this->request->userAgent() ?? '',
method: $this->request->method(),
headers: $this->fieldMasker->mask(
HeaderFilter::filter($this->request->headers->all(), config('treblle.excluded_headers', []))
),
query: $this->fieldMasker->mask($this->request->query->all()),
body: $this->fieldMasker->mask($this->getRequestBody()),
route_path: $this->request->route()?->toSymfonyRoute()->getPath(),
);
}
/**
* Get the request body with priority for original payload.
*
* Returns the original unmodified request payload if it was captured by
* TreblleEarlyMiddleware. Otherwise, returns the current request data.
* This ensures accurate logging even when middleware or form requests
* modify the payload.
*
* @return array The request body data
*/
private function getRequestBody(): array
{
// Prioritizing original payload if captured by TreblleEarlyMiddleware.
if ($this->request->attributes->has('treblle_original_payload')) {
return $this->request->attributes->get('treblle_original_payload');
}
// Try toArray() first (supports JSON requests), fallback to all() for GET/multipart
try {
return $this->request->toArray();
} catch (Throwable $e) {
// toArray() throws BadMethodCallException for GET requests and ValidationException
// for malformed JSON. Fall back to all() which safely returns all input.
return $this->request->all();
}
}
}
| php | MIT | 835166e5363913f2377b1e2ed992ce679035f8fd | 2026-01-05T05:01:19.522984Z | false |
Treblle/treblle-laravel | https://github.com/Treblle/treblle-laravel/blob/835166e5363913f2377b1e2ed992ce679035f8fd/src/DataProviders/LaravelResponseDataProvider.php | src/DataProviders/LaravelResponseDataProvider.php | <?php
declare(strict_types=1);
namespace Treblle\Laravel\DataProviders;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Treblle\Php\Helpers\HeaderFilter;
use Treblle\Php\DataTransferObject\Error;
use Treblle\Php\Contract\ErrorDataProvider;
use Treblle\Php\DataTransferObject\Response;
use Treblle\Php\Helpers\SensitiveDataMasker;
use Treblle\Php\Contract\ResponseDataProvider;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
/**
* Laravel-specific Response Data Provider for Treblle.
*
* Implements the ResponseDataProvider contract from treblle-php to extract
* and format response data from Laravel/Symfony response objects. Handles
* sensitive data masking, header filtering, response size validation, and
* accurate load time calculation.
*
* @package Treblle\Laravel\DataProviders
*/
final class LaravelResponseDataProvider implements ResponseDataProvider
{
/**
* Create a new Laravel response data provider instance.
*
* @param SensitiveDataMasker $fieldMasker Masker for sensitive data fields
* @param Request|SymfonyRequest $request The Laravel/Symfony request object
* @param JsonResponse|\Illuminate\Http\Response|SymfonyResponse $response The Laravel/Symfony response object
* @param ErrorDataProvider $errorDataProvider Reference to error data provider for logging issues
*/
public function __construct(
private readonly SensitiveDataMasker $fieldMasker,
private Request|SymfonyRequest $request,
private readonly JsonResponse|\Illuminate\Http\Response|SymfonyResponse $response,
private ErrorDataProvider &$errorDataProvider,
) {
}
/**
* Extract and format response data for Treblle.
*
* Builds a Response DTO containing all relevant response information including
* status code, body size, load time, headers (filtered and masked), and response
* body (masked). Validates response size and logs an error if it exceeds 2MB.
*
* @return Response The formatted response data transfer object
*/
public function getResponse(): Response
{
$body = $this->response->getContent();
$size = mb_strlen($body);
if ($size > 2 * 1024 * 1024) {
$body = '{}';
$size = 0;
$this->errorDataProvider->addError(new Error(
message: 'JSON response size is over 2MB',
file: '',
line: 0,
type: 'E_USER_ERROR'
));
}
return new Response(
code: $this->response->getStatusCode(),
size: $size,
load_time: $this->getLoadTimeInMilliseconds(),
body: $this->fieldMasker->mask(
json_decode($body, true) ?? []
),
headers: $this->fieldMasker->mask(
HeaderFilter::filter($this->response->headers->all(), config('treblle.excluded_headers', []))
),
);
}
/**
* Calculate the request load time in milliseconds.
*
* Determines the total time taken to process the request by checking multiple
* sources in order of accuracy:
* 1. Custom timestamp set by Laravel Octane event listener (most accurate for Octane)
* 2. PHP's REQUEST_TIME_FLOAT server variable
* 3. Laravel's LARAVEL_START constant
*
* @return float The load time in milliseconds
*/
private function getLoadTimeInMilliseconds(): float
{
$currentTimeInMilliseconds = microtime(true) * 1000;
$requestTimeInMilliseconds = microtime(true) * 1000;
if ($this->request->attributes->has('treblle_request_started_at')) {
$requestTimeInMilliseconds = $this->request->attributes->get('treblle_request_started_at') * 1000;
return $currentTimeInMilliseconds - $requestTimeInMilliseconds;
}
if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
$requestTimeInMilliseconds = (float)$_SERVER['REQUEST_TIME_FLOAT'] * 1000;
} elseif (defined('LARAVEL_START')) {
$requestTimeInMilliseconds = LARAVEL_START * 1000;
}
return $currentTimeInMilliseconds - $requestTimeInMilliseconds;
}
}
| php | MIT | 835166e5363913f2377b1e2ed992ce679035f8fd | 2026-01-05T05:01:19.522984Z | false |
Treblle/treblle-laravel | https://github.com/Treblle/treblle-laravel/blob/835166e5363913f2377b1e2ed992ce679035f8fd/src/Middlewares/TreblleMiddleware.php | src/Middlewares/TreblleMiddleware.php | <?php
declare(strict_types=1);
namespace Treblle\Laravel\Middlewares;
use Closure;
use Throwable;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Treblle\Php\Factory\TreblleFactory;
use Treblle\Php\DataTransferObject\Data;
use Treblle\Laravel\Jobs\SendTreblleData;
use Treblle\Php\DataTransferObject\Error;
use Treblle\Laravel\TreblleServiceProvider;
use Treblle\Php\Helpers\SensitiveDataMasker;
use Treblle\Php\DataProviders\PhpLanguageDataProvider;
use Treblle\Php\DataProviders\InMemoryErrorDataProvider;
use Treblle\Laravel\DataTransferObject\TrebllePayloadData;
use Treblle\Laravel\DataProviders\LaravelRequestDataProvider;
use Treblle\Php\DataProviders\SuperGlobalsServerDataProvider;
use Treblle\Laravel\DataProviders\LaravelResponseDataProvider;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
/**
* Treblle Monitoring Middleware for Laravel Applications.
*
* This middleware captures and sends API request/response data to Treblle for monitoring
* and observability. It uses Laravel's terminable middleware pattern to transmit data
* after the response has been sent to the client, ensuring zero impact on response times.
*
* Features:
* - Environment-based toggle (enable/disable monitoring)
* - Ignored environments support (dev, test, etc.)
* - Dynamic API key override per route
* - Sensitive data masking
* - Exception tracking
* - Non-blocking data transmission
*
* @package Treblle\Laravel\Middlewares
*/
final class TreblleMiddleware
{
/**
* Cached configuration values for performance optimization.
*/
private bool $enabled;
private array $ignoredEnvironments;
private bool $queueEnabled;
private ?string $queueConnection;
private string $queueName;
private array $maskedFields;
private bool $debug;
/**
* Initialize middleware with cached configuration.
*/
public function __construct()
{
$this->enabled = (bool) config('treblle.enable', true);
// Parse ignored environments once and create hash map for O(1) lookups
$ignoredEnvs = array_map('trim', explode(',', config('treblle.ignored_environments', '') ?? ''));
$this->ignoredEnvironments = array_flip($ignoredEnvs);
$this->queueEnabled = (bool) config('treblle.queue.enabled', false);
$this->queueConnection = config('treblle.queue.connection');
$this->queueName = config('treblle.queue.queue', 'default');
$this->maskedFields = (array) config('treblle.masked_fields', []);
$this->debug = (bool) config('treblle.debug', false);
}
/**
* Handle an incoming request.
*
* Validates Treblle configuration (SDK token and API key) and optionally
* overrides the API key for specific routes. The middleware respects the
* `enable` flag and `ignored_environments` configuration to determine
* whether monitoring should be active.
*
* Uses Laravel's terminable middleware pattern - actual data transmission
* happens in terminate() after the response has been sent to the client.
*
* IMPORTANT: This middleware NEVER throws exceptions. Missing configuration
* results in silent failure (with debug logging) to ensure Treblle never
* breaks your API.
*
* @param Request $request The incoming HTTP request
* @param Closure $next The next middleware in the pipeline
* @param string|null $apiKey Optional API key override for this specific route
*
* @return mixed The response from the next middleware
*/
public function handle(Request $request, Closure $next, string|null $apiKey = null)
{
if (! $this->enabled) {
return $next($request);
}
// O(1) hash lookup instead of O(n) in_array
if (isset($this->ignoredEnvironments[app()->environment()])) {
return $next($request);
}
if (null !== $apiKey) {
config(['treblle.api_key' => $apiKey]);
}
// Validate configuration - fail silently if missing to never break the API
if (! config('treblle.sdk_token')) {
$this->logConfigError('TREBLLE_SDK_TOKEN is not configured. Treblle monitoring disabled.');
return $next($request);
}
if (! config('treblle.api_key')) {
$this->logConfigError('TREBLLE_API_KEY is not configured. Treblle monitoring disabled.');
return $next($request);
}
// Pass request through immediately - data transmission happens in terminate()
return $next($request);
}
/**
* Perform any final actions for the request lifecycle.
*
* @param Request $request The HTTP request that was processed
* @param JsonResponse|Response|SymfonyResponse $response The response that was sent
*
* @return void
*/
public function terminate(Request $request, JsonResponse|Response|SymfonyResponse $response): void
{
// O(1) hash lookup for ignored environments
if (isset($this->ignoredEnvironments[app()->environment()])) {
return;
}
// Re-validate configuration (in case it was changed after handle())
if (! config('treblle.sdk_token') || ! config('treblle.api_key')) {
return;
}
// Queue mode: dispatch to background job for async processing
if ($this->queueEnabled) {
$this->dispatchToQueue($request, $response);
return;
}
// Synchronous mode: send directly to Treblle
$this->sendSynchronously($request, $response);
}
/**
* Dispatch Treblle data to queue for background processing.
*
* Wrapped in try-catch to ensure Treblle never breaks the application.
*
* @param Request $request The HTTP request
* @param JsonResponse|Response|SymfonyResponse $response The HTTP response
*
* @return void
*/
private function dispatchToQueue(Request $request, JsonResponse|Response|SymfonyResponse $response): void
{
try {
// Extract data from Request/Response BEFORE queuing to avoid serialization issues
$fieldMasker = new SensitiveDataMasker($this->maskedFields);
$errorProvider = new InMemoryErrorDataProvider();
$requestProvider = new LaravelRequestDataProvider($fieldMasker, $request);
$responseProvider = new LaravelResponseDataProvider($fieldMasker, $request, $response, $errorProvider);
// Use core SDK providers for Server and Language data
$serverProvider = new SuperGlobalsServerDataProvider();
$languageProvider = new PhpLanguageDataProvider();
// Capture exception data if present
if (! empty($response->exception)) {
$errorProvider->addError(new Error(
$response->exception->getMessage(),
$response->exception->getFile(),
$response->exception->getLine(),
'onException',
'UNHANDLED_EXCEPTION',
));
}
// Build serializable DTO with extracted data
$payloadData = new TrebllePayloadData(
apiKey: (string) config('treblle.api_key'),
sdkToken: (string) config('treblle.sdk_token'),
sdkName: TreblleServiceProvider::SDK_NAME,
sdkVersion: TreblleServiceProvider::SDK_VERSION,
data: new Data(
$serverProvider->getServer(),
$languageProvider->getLanguage(),
$requestProvider->getRequest(),
$responseProvider->getResponse(),
$errorProvider->getErrors()
),
url: config('treblle.url'),
debug: $this->debug
);
// Create and dispatch job with serializable data
$job = new SendTreblleData($payloadData);
if ($this->queueConnection) {
$job->onConnection($this->queueConnection);
}
$job->onQueue($this->queueName);
dispatch($job);
} catch (Throwable $e) {
$this->logError('Treblle queue dispatch failed', $e);
}
}
/**
* Send Treblle data synchronously using the core SDK.
*
* Wrapped in try-catch to ensure Treblle never breaks the application.
*
* @param Request $request The HTTP request
* @param JsonResponse|Response|SymfonyResponse $response The HTTP response
*
* @return void
*/
private function sendSynchronously(Request $request, JsonResponse|Response|SymfonyResponse $response): void
{
try {
// Use cached config values
$fieldMasker = new SensitiveDataMasker($this->maskedFields);
$errorProvider = new InMemoryErrorDataProvider();
$requestProvider = new LaravelRequestDataProvider($fieldMasker, $request);
$responseProvider = new LaravelResponseDataProvider($fieldMasker, $request, $response, $errorProvider);
if (! empty($response->exception)) {
$errorProvider->addError(new Error(
$response->exception->getMessage(),
$response->exception->getFile(),
$response->exception->getLine(),
'onException',
'UNHANDLED_EXCEPTION',
));
}
$treblle = TreblleFactory::create(
apiKey: (string) config('treblle.api_key'),
sdkToken: (string) config('treblle.sdk_token'),
debug: $this->debug,
maskedFields: $this->maskedFields,
config: [
'url' => config('treblle.url'),
'register_handlers' => false,
'fork_process' => false,
'request_provider' => $requestProvider,
'response_provider' => $responseProvider,
'error_provider' => $errorProvider,
]
);
// Manually execute onShutdown because on octane server never shuts down
// so registered shutdown function never gets called
// hence we have disabled handlers using config register_handlers
$treblle
->setName(TreblleServiceProvider::SDK_NAME)
->setVersion(TreblleServiceProvider::SDK_VERSION)
->onShutdown();
} catch (Throwable $e) {
$this->logError('Treblle synchronous transmission failed', $e);
}
}
/**
* Log configuration errors when debug mode is enabled.
*
* @param string $message The error message
*
* @return void
*/
private function logConfigError(string $message): void
{
if ($this->debug) {
logger()->warning('[Treblle] ' . $message);
}
}
/**
* Log runtime errors when debug mode is enabled.
*
* @param string $message The error message
* @param Throwable $exception The exception that was thrown
*
* @return void
*/
private function logError(string $message, Throwable $exception): void
{
if ($this->debug) {
logger()->error('[Treblle] ' . $message, [
'exception' => get_class($exception),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
]);
}
}
}
| php | MIT | 835166e5363913f2377b1e2ed992ce679035f8fd | 2026-01-05T05:01:19.522984Z | false |
Treblle/treblle-laravel | https://github.com/Treblle/treblle-laravel/blob/835166e5363913f2377b1e2ed992ce679035f8fd/src/Middlewares/TreblleEarlyMiddleware.php | src/Middlewares/TreblleEarlyMiddleware.php | <?php
declare(strict_types=1);
namespace Treblle\Laravel\Middlewares;
use Closure;
use Illuminate\Http\Request;
/**
* Early Capture Middleware for Treblle Monitoring.
*
* This middleware captures the original request payload before any transformations,
* validations, or modifications occur in subsequent middleware or controllers. This
* ensures Treblle can log the exact data as it was received by the application.
*
* Usage:
* Register this middleware with high priority (it's automatically prepended to
* middleware priority list by TreblleServiceProvider) or apply it to specific
* routes that require original payload capture.
*
* @package Treblle\Laravel\Middlewares
*/
final class TreblleEarlyMiddleware
{
/**
* Handle an incoming request and capture original payload.
*
* Stores the unmodified request payload in request attributes before any
* subsequent middleware or application logic can transform it. This is
* particularly useful for:
* - Form requests with validation
* - Middleware that modifies request data
* - Controllers that mutate input before processing
*
* @param Request $request The incoming HTTP request
* @param Closure $next The next middleware in the pipeline
*
* @return mixed The response from the next middleware
*/
public function handle(Request $request, Closure $next)
{
$request->attributes->set('treblle_original_payload', $request->all());
return $next($request);
}
}
| php | MIT | 835166e5363913f2377b1e2ed992ce679035f8fd | 2026-01-05T05:01:19.522984Z | false |
Treblle/treblle-laravel | https://github.com/Treblle/treblle-laravel/blob/835166e5363913f2377b1e2ed992ce679035f8fd/src/DataTransferObject/TrebllePayloadData.php | src/DataTransferObject/TrebllePayloadData.php | <?php
declare(strict_types=1);
namespace Treblle\Laravel\DataTransferObject;
use Treblle\Php\DataTransferObject\Data;
/**
* Data Transfer Object for Treblle payload.
*
* This DTO holds the complete extracted payload data that can be safely
* serialized and passed to queue jobs. By extracting data from Request/Response
* objects before queuing, we avoid serialization issues with Closures and
* other non-serializable properties.
*
* @package Treblle\Laravel\DataTransferObject
*/
final readonly class TrebllePayloadData
{
/**
* Create a new TrebllePayloadData instance.
*
* @param string $apiKey The Treblle API key
* @param string $sdkToken The Treblle SDK token
* @param string $sdkName The SDK name
* @param float $sdkVersion The SDK version
* @param Data $data The core Treblle data object containing request/response/errors
* @param string|null $url Optional custom Treblle endpoint URL
* @param bool $debug Whether debug mode is enabled
*/
public function __construct(
public string $apiKey,
public string $sdkToken,
public string $sdkName,
public float $sdkVersion,
public Data $data,
public string|null $url = null,
public bool $debug = false
) {
}
/**
* Convert to array format for JSON encoding.
*
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'api_key' => $this->apiKey,
'sdk_token' => $this->sdkToken,
'sdk' => $this->sdkName,
'version' => $this->sdkVersion,
'data' => $this->data,
];
}
}
| php | MIT | 835166e5363913f2377b1e2ed992ce679035f8fd | 2026-01-05T05:01:19.522984Z | false |
Treblle/treblle-laravel | https://github.com/Treblle/treblle-laravel/blob/835166e5363913f2377b1e2ed992ce679035f8fd/tests/TestCase.php | tests/TestCase.php | <?php
declare(strict_types=1);
namespace Treblle\Laravel\Tests;
use Orchestra\Testbench\TestCase as BaseTestCase;
final class TestCase extends BaseTestCase
{
}
| php | MIT | 835166e5363913f2377b1e2ed992ce679035f8fd | 2026-01-05T05:01:19.522984Z | false |
Treblle/treblle-laravel | https://github.com/Treblle/treblle-laravel/blob/835166e5363913f2377b1e2ed992ce679035f8fd/config/treblle.php | config/treblle.php | <?php
declare(strict_types=1);
return [
/*
* Enable or disable Treblle monitoring
*/
'enable' => env('TREBLLE_ENABLE', true),
/*
* An override while debugging.
*/
'url' => null,
/*
* Your Treblle SDK Token. You can get started for FREE by visiting https://treblle.com/
* In v5: Previously called 'api_key'
*/
'sdk_token' => env('TREBLLE_SDK_TOKEN'),
/*
* Your Treblle API Key. Create your first project on https://treblle.com/
* In v5: Previously called 'project_id'
*/
'api_key' => env('TREBLLE_API_KEY'),
/*
* Define which environments should Treblle ignore and not monitor
*/
'ignored_environments' => env('TREBLLE_IGNORED_ENV', 'dev,test,testing'),
/*
* Define which fields should be masked before leaving the server
*/
'masked_fields' => [
'password',
'pwd',
'secret',
'password_confirmation',
'cc',
'card_number',
'ccv',
'ssn',
'credit_score',
'api_key',
],
/*
* Define which headers should be excluded from logging
*/
'excluded_headers' => [],
/*
* Should be used in development mode only.
* Enable Debug mode, will throw errors on apis.
*/
'debug' => env('TREBLLE_DEBUG_MODE', false),
/*
* Queue Configuration
*
* Enable asynchronous data transmission using Laravel queues.
* When enabled, Treblle data will be sent via jobs instead of synchronously.
*
* Supported connections: redis, sqs, beanstalkd, database (with proper indexes)
* Not recommended: sync, file (slow and unreliable)
*/
'queue' => [
/*
* Enable queue-based data transmission
*/
'enabled' => env('TREBLLE_QUEUE_ENABLED', false),
/*
* Queue connection to use (must be configured in config/queue.php)
* If null, uses the default queue connection
* Recommended: redis, sqs, beanstalkd
*/
'connection' => env('TREBLLE_QUEUE_CONNECTION', 'redis'),
/*
* Queue name to dispatch jobs to
* If null, uses the default queue for the connection
*/
'queue' => env('TREBLLE_QUEUE_NAME', 'default'),
],
];
| php | MIT | 835166e5363913f2377b1e2ed992ce679035f8fd | 2026-01-05T05:01:19.522984Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/server.php | server.php | <?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Producto.php | app/Producto.php | <?php
/*
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
Blog: https://parzibyte.me/blog
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/
Contacto: https://parzibyte.me/blog/contacto/
Copyright (c) 2020 Luis Cabrera Benito
Licenciado bajo la licencia MIT
El texto de arriba debe ser incluido en cualquier redistribucion
*/ ?>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Producto extends Model
{
protected $fillable = ["codigo_barras", "descripcion", "precio_compra", "precio_venta", "existencia",
];
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/User.php | app/User.php | <?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/ProductoVendido.php | app/ProductoVendido.php | <?php
/*
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
Blog: https://parzibyte.me/blog
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/
Contacto: https://parzibyte.me/blog/contacto/
Copyright (c) 2020 Luis Cabrera Benito
Licenciado bajo la licencia MIT
El texto de arriba debe ser incluido en cualquier redistribucion
*/ ?>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ProductoVendido extends Model
{
protected $table = "productos_vendidos";
protected $fillable = ["id_venta", "descripcion", "codigo_barras", "precio", "cantidad"];
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Venta.php | app/Venta.php | <?php
/*
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
Blog: https://parzibyte.me/blog
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/
Contacto: https://parzibyte.me/blog/contacto/
Copyright (c) 2020 Luis Cabrera Benito
Licenciado bajo la licencia MIT
El texto de arriba debe ser incluido en cualquier redistribucion
*/ ?>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Venta extends Model
{
public function productos()
{
return $this->hasMany("App\ProductoVendido", "id_venta");
}
public function cliente()
{
return $this->belongsTo("App\Cliente", "id_cliente");
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Cliente.php | app/Cliente.php | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cliente extends Model
{
protected $fillable = ["nombre", "telefono"];
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Exceptions/Handler.php | app/Exceptions/Handler.php | <?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* @param \Throwable $exception
* @return void
*
* @throws \Exception
*/
public function report(Throwable $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Throwable
*/
public function render($request, Throwable $exception)
{
return parent::render($request, $exception);
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Kernel.php | app/Http/Kernel.php | <?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/VentasController.php | app/Http/Controllers/VentasController.php | <?php
/*
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
Blog: https://parzibyte.me/blog
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/
Contacto: https://parzibyte.me/blog/contacto/
Copyright (c) 2020 Luis Cabrera Benito
Licenciado bajo la licencia MIT
El texto de arriba debe ser incluido en cualquier redistribucion
*/ ?>
<?php
namespace App\Http\Controllers;
use App\Venta;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
use Mike42\Escpos\Printer;
class VentasController extends Controller
{
public function ticket(Request $request)
{
$venta = Venta::findOrFail($request->get("id"));
$nombreImpresora = env("NOMBRE_IMPRESORA");
$connector = new WindowsPrintConnector($nombreImpresora);
$impresora = new Printer($connector);
$impresora->setJustification(Printer::JUSTIFY_CENTER);
$impresora->setEmphasis(true);
$impresora->text("Ticket de venta\n");
$impresora->text($venta->created_at . "\n");
$impresora->setEmphasis(false);
$impresora->text("Cliente: ");
$impresora->text($venta->cliente->nombre . "\n");
$impresora->text("\nhttps://parzibyte.me/blog\n");
$impresora->text("\n===============================\n");
$total = 0;
foreach ($venta->productos as $producto) {
$subtotal = $producto->cantidad * $producto->precio;
$total += $subtotal;
$impresora->setJustification(Printer::JUSTIFY_LEFT);
$impresora->text(sprintf("%.2fx%s\n", $producto->cantidad, $producto->descripcion));
$impresora->setJustification(Printer::JUSTIFY_RIGHT);
$impresora->text('$' . number_format($subtotal, 2) . "\n");
}
$impresora->setJustification(Printer::JUSTIFY_CENTER);
$impresora->text("\n===============================\n");
$impresora->setJustification(Printer::JUSTIFY_RIGHT);
$impresora->setEmphasis(true);
$impresora->text("Total: $" . number_format($total, 2) . "\n");
$impresora->setJustification(Printer::JUSTIFY_CENTER);
$impresora->setTextSize(1, 1);
$impresora->text("Gracias por su compra\n");
$impresora->text("https://parzibyte.me/blog");
$impresora->feed(5);
$impresora->close();
return redirect()->back()->with("mensaje", "Ticket impreso");
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$ventasConTotales = Venta::join("productos_vendidos", "productos_vendidos.id_venta", "=", "ventas.id")
->select("ventas.*", DB::raw("sum(productos_vendidos.cantidad * productos_vendidos.precio) as total"))
->groupBy("ventas.id", "ventas.created_at", "ventas.updated_at", "ventas.id_cliente")
->get();
return view("ventas.ventas_index", ["ventas" => $ventasConTotales,]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param \App\Venta $venta
* @return \Illuminate\Http\Response
*/
public function show(Venta $venta)
{
$total = 0;
foreach ($venta->productos as $producto) {
$total += $producto->cantidad * $producto->precio;
}
return view("ventas.ventas_show", [
"venta" => $venta,
"total" => $total,
]);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Venta $venta
* @return \Illuminate\Http\Response
*/
public function edit(Venta $venta)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Venta $venta
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Venta $venta)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Venta $venta
* @return \Illuminate\Http\Response
*/
public function destroy(Venta $venta)
{
$venta->delete();
return redirect()->route("ventas.index")
->with("mensaje", "Venta eliminada");
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/ProductosController.php | app/Http/Controllers/ProductosController.php | <?php
/*
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
Blog: https://parzibyte.me/blog
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/
Contacto: https://parzibyte.me/blog/contacto/
Copyright (c) 2020 Luis Cabrera Benito
Licenciado bajo la licencia MIT
El texto de arriba debe ser incluido en cualquier redistribucion
*/ ?>
<?php
namespace App\Http\Controllers;
use App\Producto;
use Illuminate\Http\Request;
class ProductosController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view("productos.productos_index", ["productos" => Producto::all()]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view("productos.productos_create");
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$producto = new Producto($request->input());
$producto->saveOrFail();
return redirect()->route("productos.index")->with("mensaje", "Producto guardado");
}
/**
* Display the specified resource.
*
* @param \App\Producto $producto
* @return \Illuminate\Http\Response
*/
public function show(Producto $producto)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Producto $producto
* @return \Illuminate\Http\Response
*/
public function edit(Producto $producto)
{
return view("productos.productos_edit", ["producto" => $producto,
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Producto $producto
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Producto $producto)
{
$producto->fill($request->input());
$producto->saveOrFail();
return redirect()->route("productos.index")->with("mensaje", "Producto actualizado");
}
/**
* Remove the specified resource from storage.
*
* @param \App\Producto $producto
* @return \Illuminate\Http\Response
*/
public function destroy(Producto $producto)
{
$producto->delete();
return redirect()->route("productos.index")->with("mensaje", "Producto eliminado");
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/Controller.php | app/Http/Controllers/Controller.php | <?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/UserController.php | app/Http/Controllers/UserController.php | <?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view("usuarios.usuarios_index", ["usuarios" => User::all()]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view("usuarios.usuarios_create");
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$usuario = new User($request->input());
$usuario->password = Hash::make($usuario->password);
$usuario->saveOrFail();
return redirect()->route("usuarios.index")->with("mensaje", "Usuario guardado");
}
/**
* Display the specified resource.
*
* @param \App\User $user
* @return \Illuminate\Http\Response
*/
public function show(User $user)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\User $user
* @return \Illuminate\Http\Response
*/
public function edit(User $user)
{
$user->password = "";
return view("usuarios.usuarios_edit", ["usuario" => $user,
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\User $user
* @return \Illuminate\Http\Response
*/
public function update(Request $request, User $user)
{
$user->fill($request->input());
$user->password = Hash::make($user->password);
$user->saveOrFail();
return redirect()->route("usuarios.index")->with("mensaje", "Usuario actualizado");
}
/**
* Remove the specified resource from storage.
*
* @param \App\User $user
* @return \Illuminate\Http\Response
*/
public function destroy(User $user)
{
$user->delete();
return redirect()->route("usuarios.index")->with("mensaje", "Usuario eliminado");
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/AuthController.php | app/Http/Controllers/AuthController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function signup(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed',
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'], 201);
}
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean',
]);
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials)) {
return response()->json([
'message' => 'Unauthorized'], 401);
}
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me) {
$token->expires_at = Carbon::now()->addWeeks(1);
}
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at)
->toDateTimeString(),
]);
}
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json(['message' =>
'Successfully logged out']);
}
public function user(Request $request)
{
return response()->json($request->user());
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/HomeController.php | app/Http/Controllers/HomeController.php | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/VenderController.php | app/Http/Controllers/VenderController.php | <?php
/*
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
Blog: https://parzibyte.me/blog
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/
Contacto: https://parzibyte.me/blog/contacto/
Copyright (c) 2020 Luis Cabrera Benito
Licenciado bajo la licencia MIT
El texto de arriba debe ser incluido en cualquier redistribucion
*/ ?>
<?php
namespace App\Http\Controllers;
use App\Cliente;
use App\Producto;
use App\ProductoVendido;
use App\Venta;
use Illuminate\Http\Request;
class VenderController extends Controller
{
public function terminarOCancelarVenta(Request $request)
{
if ($request->input("accion") == "terminar") {
return $this->terminarVenta($request);
} else {
return $this->cancelarVenta();
}
}
public function terminarVenta(Request $request)
{
// Crear una venta
$venta = new Venta();
$venta->id_cliente = $request->input("id_cliente");
$venta->saveOrFail();
$idVenta = $venta->id;
$productos = $this->obtenerProductos();
// Recorrer carrito de compras
foreach ($productos as $producto) {
// El producto que se vende...
$productoVendido = new ProductoVendido();
$productoVendido->fill([
"id_venta" => $idVenta,
"descripcion" => $producto->descripcion,
"codigo_barras" => $producto->codigo_barras,
"precio" => $producto->precio_venta,
"cantidad" => $producto->cantidad,
]);
// Lo guardamos
$productoVendido->saveOrFail();
// Y restamos la existencia del original
$productoActualizado = Producto::find($producto->id);
$productoActualizado->existencia -= $productoVendido->cantidad;
$productoActualizado->saveOrFail();
}
$this->vaciarProductos();
return redirect()
->route("vender.index")
->with("mensaje", "Venta terminada");
}
private function obtenerProductos()
{
$productos = session("productos");
if (!$productos) {
$productos = [];
}
return $productos;
}
private function vaciarProductos()
{
$this->guardarProductos(null);
}
private function guardarProductos($productos)
{
session(["productos" => $productos,
]);
}
public function cancelarVenta()
{
$this->vaciarProductos();
return redirect()
->route("vender.index")
->with("mensaje", "Venta cancelada");
}
public function quitarProductoDeVenta(Request $request)
{
$indice = $request->post("indice");
$productos = $this->obtenerProductos();
array_splice($productos, $indice, 1);
$this->guardarProductos($productos);
return redirect()
->route("vender.index");
}
public function agregarProductoVenta(Request $request)
{
$codigo = $request->post("codigo");
$producto = Producto::where("codigo_barras", "=", $codigo)->first();
if (!$producto) {
return redirect()
->route("vender.index")
->with("mensaje", "Producto no encontrado");
}
$this->agregarProductoACarrito($producto);
return redirect()
->route("vender.index");
}
private function agregarProductoACarrito($producto)
{
if ($producto->existencia <= 0) {
return redirect()->route("vender.index")
->with([
"mensaje" => "No hay existencias del producto",
"tipo" => "danger"
]);
}
$productos = $this->obtenerProductos();
$posibleIndice = $this->buscarIndiceDeProducto($producto->codigo_barras, $productos);
// Es decir, producto no fue encontrado
if ($posibleIndice === -1) {
$producto->cantidad = 1;
array_push($productos, $producto);
} else {
if ($productos[$posibleIndice]->cantidad + 1 > $producto->existencia) {
return redirect()->route("vender.index")
->with([
"mensaje" => "No se pueden agregar más productos de este tipo, se quedarían sin existencia",
"tipo" => "danger"
]);
}
$productos[$posibleIndice]->cantidad++;
}
$this->guardarProductos($productos);
}
private function buscarIndiceDeProducto(string $codigo, array &$productos)
{
foreach ($productos as $indice => $producto) {
if ($producto->codigo_barras === $codigo) {
return $indice;
}
}
return -1;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$total = 0;
foreach ($this->obtenerProductos() as $producto) {
$total += $producto->cantidad * $producto->precio_venta;
}
return view("vender.vender",
[
"total" => $total,
"clientes" => Cliente::all(),
]);
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/ClientesController.php | app/Http/Controllers/ClientesController.php | <?php
namespace App\Http\Controllers;
use App\Cliente;
use Illuminate\Http\Request;
class ClientesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view("clientes.clientes_index", ["clientes" => Cliente::all()]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view("clientes.clientes_create");
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
(new Cliente($request->input()))->saveOrFail();
return redirect()->route("clientes.index")->with("mensaje", "Cliente agregado");
}
/**
* Display the specified resource.
*
* @param \App\Cliente $cliente
* @return \Illuminate\Http\Response
*/
public function show(Cliente $cliente)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Cliente $cliente
* @return \Illuminate\Http\Response
*/
public function edit(Cliente $cliente)
{
return view("clientes.clientes_edit", ["cliente" => $cliente]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Cliente $cliente
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Cliente $cliente)
{
$cliente->fill($request->input());
$cliente->saveOrFail();
return redirect()->route("clientes.index")->with("mensaje", "Cliente actualizado");
}
/**
* Remove the specified resource from storage.
*
* @param \App\Cliente $cliente
* @return \Illuminate\Http\Response
*/
public function destroy(Cliente $cliente)
{
$cliente->delete();
return redirect()->route("clientes.index")->with("mensaje", "Cliente eliminado");
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/Auth/ConfirmPasswordController.php | app/Http/Controllers/Auth/ConfirmPasswordController.php | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ConfirmsPasswords;
class ConfirmPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Confirm Password Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password confirmations and
| uses a simple trait to include the behavior. You're free to explore
| this trait and override any functions that require customization.
|
*/
use ConfirmsPasswords;
/**
* Where to redirect users when the intended url fails.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/Auth/LoginController.php | app/Http/Controllers/Auth/LoginController.php | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/Auth/VerificationController.php | app/Http/Controllers/Auth/VerificationController.php | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\VerifiesEmails;
class VerificationController extends Controller
{
/*
|--------------------------------------------------------------------------
| Email Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
use VerifiesEmails;
/**
* Where to redirect users after verification.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('signed')->only('verify');
$this->middleware('throttle:6,1')->only('verify', 'resend');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/Auth/ForgotPasswordController.php | app/Http/Controllers/Auth/ForgotPasswordController.php | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class ForgotPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/
use SendsPasswordResetEmails;
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/Auth/ResetPasswordController.php | app/Http/Controllers/Auth/ResetPasswordController.php | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Controllers/Auth/RegisterController.php | app/Http/Controllers/Auth/RegisterController.php | <?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Middleware/Authenticate.php | app/Http/Middleware/Authenticate.php | <?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Middleware/RedirectIfAuthenticated.php | app/Http/Middleware/RedirectIfAuthenticated.php | <?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Middleware/TrustProxies.php | app/Http/Middleware/TrustProxies.php | <?php
namespace App\Http\Middleware;
use Fideloper\Proxy\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Middleware/TrimStrings.php | app/Http/Middleware/TrimStrings.php | <?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
'password',
'password_confirmation',
];
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Middleware/CheckForMaintenanceMode.php | app/Http/Middleware/CheckForMaintenanceMode.php | <?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Middleware/EncryptCookies.php | app/Http/Middleware/EncryptCookies.php | <?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Http/Middleware/VerifyCsrfToken.php | app/Http/Middleware/VerifyCsrfToken.php | <?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Console/Kernel.php | app/Console/Kernel.php | <?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Providers/BroadcastServiceProvider.php | app/Providers/BroadcastServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Providers/RouteServiceProvider.php | app/Providers/RouteServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* The path to the "home" route for your application.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Providers/EventServiceProvider.php | app/Providers/EventServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Providers/AppServiceProvider.php | app/Providers/AppServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/app/Providers/AuthServiceProvider.php | app/Providers/AuthServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/bootstrap/app.php | bootstrap/app.php | <?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/tests/TestCase.php | tests/TestCase.php | <?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/tests/CreatesApplication.php | tests/CreatesApplication.php | <?php
namespace Tests;
use Illuminate\Contracts\Console\Kernel;
trait CreatesApplication
{
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
return $app;
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/tests/Feature/ExampleTest.php | tests/Feature/ExampleTest.php | <?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/tests/Unit/ExampleTest.php | tests/Unit/ExampleTest.php | <?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$this->assertTrue(true);
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/routes/web.php | routes/web.php | <?php
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return redirect()->route("home");
});
Route::get("/acerca-de", function () {
return view("misc.acerca_de");
})->name("acerca_de.index");
Route::get("/soporte", function(){
return redirect("https://parzibyte.me/blog/contrataciones-ayuda/");
})->name("soporte.index");
Auth::routes([
"reset" => false,// no pueden olvidar contraseña
]);
Route::get('/home', 'HomeController@index')->name('home');
// Permitir logout con petición get
Route::get("/logout", function () {
Auth::logout();
return redirect()->route("home");
})->name("logout");
Route::middleware("auth")
->group(function () {
Route::resource("clientes", "ClientesController");
Route::resource("usuarios", "UserController")->parameters(["usuarios" => "user"]);
Route::resource("productos", "ProductosController");
Route::get("/ventas/ticket", "VentasController@ticket")->name("ventas.ticket");
Route::resource("ventas", "VentasController");
Route::get("/vender", "VenderController@index")->name("vender.index");
Route::post("/productoDeVenta", "VenderController@agregarProductoVenta")->name("agregarProductoVenta");
Route::delete("/productoDeVenta", "VenderController@quitarProductoDeVenta")->name("quitarProductoDeVenta");
Route::post("/terminarOCancelarVenta", "VenderController@terminarOCancelarVenta")->name("terminarOCancelarVenta");
});
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/routes/channels.php | routes/channels.php | <?php
use Illuminate\Support\Facades\Broadcast;
/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/routes/api.php | routes/api.php | <?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use App\Producto;
use App\Cliente;
use App\Venta;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get("/status", function () {
return Auth::guard('api')->check();
});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['prefix' => 'auth'], function () {
Route::post('login', 'AuthController@login');
Route::post('signup', 'AuthController@signup');
Route::group(['middleware' => 'auth:api'], function() {
Route::get('logout', 'AuthController@logout');
Route::get('user', 'AuthController@user');
Route::get("productos", function () {
return response()->json(Producto::all());
});
/*
Si existe un dios, que me perdone por dejar todas las peticiones aquí
en lugar de separarlas a otro archivo o invocar un controlador
*/
Route::post("/producto", function(Request $request){
$producto = new Producto($request->input());
$producto->saveOrFail();
return response()->json(["data" => "true"]);
});
Route::get("/producto/{id}", function($id){
$producto = Producto::findOrFail($id);
return response()->json($producto);
});
Route::put("/producto", function(Request $request){
$producto = Producto::findOrFail($request->input("id"));
$producto->fill($request->input());
$producto->saveOrFail();
return response()->json(true);
});
Route::delete("/producto/{id}", function($id){
$producto = Producto::findOrFail($id);
$producto->delete();
return response()->json(true);
});
// Clientes
Route::get("clientes", function () {
return response()->json(Cliente::all());
});
Route::post("/cliente", function(Request $request){
$cliente = new Cliente($request->input());
$cliente->saveOrFail();
return response()->json(["data" => "true"]);
});
Route::get("/cliente/{id}", function($id){
$cliente = Cliente::findOrFail($id);
return response()->json($cliente);
});
Route::put("/cliente", function(Request $request){
$cliente = Cliente::findOrFail($request->input("id"));
$cliente->fill($request->input());
$cliente->saveOrFail();
return response()->json(true);
});
Route::delete("/cliente/{id}", function($id){
$cliente = Cliente::findOrFail($id);
$cliente->delete();
return response()->json(true);
});
// Ventas
Route::get("ventas", function () {
return response()->json(Venta::with(["productos", "cliente"])->get());
});
Route::post("/venta", function(Request $request){
$venta = new Venta($request->input());
$venta->saveOrFail();
return response()->json(["data" => "true"]);
});
Route::get("/venta/{id}", function($id){
$venta = Venta::with(["productos", "cliente"])->findOrFail($id);
return response()->json($venta);
});
Route::delete("/venta/{id}", function($id){
$venta = Venta::findOrFail($id);
$venta->delete();
return response()->json(true);
});
});
});
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/routes/console.php | routes/console.php | <?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->describe('Display an inspiring quote');
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/public/index.php | public/index.php | <?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/
require __DIR__.'/../vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/
$app = require_once __DIR__.'/../bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/app.php | config/app.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', null),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'America/Mexico_City',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'es',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Arr' => Illuminate\Support\Arr::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Http' => Illuminate\Support\Facades\Http::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'Str' => Illuminate\Support\Str::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/logging.php | config/logging.php | <?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 14,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => 'critical',
],
'papertrail' => [
'driver' => 'monolog',
'level' => 'debug',
'handler' => SyslogUdpHandler::class,
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
],
],
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/session.php | config/session.php | <?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION', null),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using the "apc", "memcached", or "dynamodb" session drivers you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
*/
'store' => env('SESSION_STORE', null),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN', null),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE', null),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| do not enable this as other CSRF protection services are in place.
|
| Supported: "lax", "strict", "none"
|
*/
'same_site' => 'lax',
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/queue.php | config/queue.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for every one. Here you may define a default connection.
|
*/
'default' => env('QUEUE_CONNECTION', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'your-queue-name'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/cache.php | config/cache.php | <?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
| Supported: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb"
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store such as APC or Memcached, there might
| be other applications utilizing the same cache. So, we'll specify a
| value to get prefixed to all our keys so we can avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'),
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/hashing.php | config/hashing.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 10),
],
/*
|--------------------------------------------------------------------------
| Argon Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Argon algorithm. These will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'argon' => [
'memory' => 1024,
'threads' => 2,
'time' => 2,
],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/view.php | config/view.php | <?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
resource_path('views'),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => env(
'VIEW_COMPILED_PATH',
realpath(storage_path('framework/views'))
),
/*
|--------------------------------------------------------------------------
| Blade View Modification Checking
|--------------------------------------------------------------------------
|
| On every request the framework will check to see if a view has expired
| to determine if it needs to be recompiled. If you are in production
| and precompiling views this feature may be disabled to save time.
|
*/
'expires' => env('VIEW_CHECK_EXPIRATION', true),
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/database.php | config/database.php | <?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'schema' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/services.php | config/services.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/filesystems.php | config/filesystems.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => env('FILESYSTEM_CLOUD', 's3'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/mail.php | config/mail.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send any email
| messages sent by your application. Alternative mailers may be setup
| and used as needed; however, this mailer will be used by default.
|
*/
'default' => env('MAIL_MAILER', 'smtp'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers to be used while
| sending an e-mail. You will specify which one you are using for your
| mailers below. You are free to add additional mailers as required.
|
| Supported: "smtp", "sendmail", "mailgun", "ses",
| "postmark", "log", "array"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
],
'ses' => [
'transport' => 'ses',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => '/usr/sbin/sendmail -bs',
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/cors.php | config/cors.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => false,
'supports_credentials' => false,
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/broadcasting.php | config/broadcasting.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => true,
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/config/auth.php | config/auth.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/database/seeds/DatabaseSeeder.php | database/seeds/DatabaseSeeder.php | <?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/database/factories/UserFactory.php | database/factories/UserFactory.php | <?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
});
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/database/migrations/2020_03_05_003009_create_ventas_table.php | database/migrations/2020_03_05_003009_create_ventas_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateVentasTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ventas', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('ventas');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/database/migrations/2020_03_05_003110_create_producto_vendidos_table.php | database/migrations/2020_03_05_003110_create_producto_vendidos_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductoVendidosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('productos_vendidos', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger("id_venta");
$table->foreign("id_venta")
->references("id")
->on("ventas")
->onDelete("cascade")
->onUpdate("cascade");
$table->string("descripcion");
$table->string("codigo_barras");
$table->decimal("precio", 9, 2);
$table->decimal("cantidad", 9, 2);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('productos_vendidos');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/database/migrations/2020_03_10_014423_create_clientes_table.php | database/migrations/2020_03_10_014423_create_clientes_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateClientesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('clientes', function (Blueprint $table) {
$table->id();
$table->string("nombre");
$table->string("telefono");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('clientes');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/database/migrations/2014_10_12_000000_create_users_table.php | database/migrations/2014_10_12_000000_create_users_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/database/migrations/2014_10_12_100000_create_password_resets_table.php | database/migrations/2014_10_12_100000_create_password_resets_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePasswordResetsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('password_resets', function (Blueprint $table) {
$table->string('email')->index();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('password_resets');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/database/migrations/2019_08_19_000000_create_failed_jobs_table.php | database/migrations/2019_08_19_000000_create_failed_jobs_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFailedJobsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('failed_jobs');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/database/migrations/2020_03_10_023628_agregar_id_cliente_ventas.php | database/migrations/2020_03_10_023628_agregar_id_cliente_ventas.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AgregarIdClienteVentas extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('ventas', function (Blueprint $table) {
$table->unsignedBigInteger('id_cliente');
$table->foreign("id_cliente")
->references("id")
->on("clientes")
->onDelete("cascade")
->onUpdate("cascade");
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('ventas', function (Blueprint $table) {
//
});
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/database/migrations/2020_03_04_190205_create_productos_table.php | database/migrations/2020_03_04_190205_create_productos_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('productos', function (Blueprint $table) {
$table->id();
$table->string("codigo_barras");
$table->string("descripcion");
$table->decimal("precio_compra", 9, 2);
$table->decimal("precio_venta", 9, 2);
$table->decimal("existencia", 9, 2);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('productos');
}
}
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/resources/lang/en/passwords.php | resources/lang/en/passwords.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Password Reset Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are given by the password broker for a password update attempt
| has failed, such as for an invalid token or invalid new password.
|
*/
'reset' => 'Your password has been reset!',
'sent' => 'We have emailed your password reset link!',
'throttled' => 'Please wait before retrying.',
'token' => 'This password reset token is invalid.',
'user' => "We can't find a user with that email address.",
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/resources/lang/en/pagination.php | resources/lang/en/pagination.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => '« Previous',
'next' => 'Next »',
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/resources/lang/en/validation.php | resources/lang/en/validation.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
'after' => 'The :attribute must be a date after :date.',
'after_or_equal' => 'The :attribute must be a date after or equal to :date.',
'alpha' => 'The :attribute may only contain letters.',
'alpha_dash' => 'The :attribute may only contain letters, numbers, dashes and underscores.',
'alpha_num' => 'The :attribute may only contain letters and numbers.',
'array' => 'The :attribute must be an array.',
'before' => 'The :attribute must be a date before :date.',
'before_or_equal' => 'The :attribute must be a date before or equal to :date.',
'between' => [
'numeric' => 'The :attribute must be between :min and :max.',
'file' => 'The :attribute must be between :min and :max kilobytes.',
'string' => 'The :attribute must be between :min and :max characters.',
'array' => 'The :attribute must have between :min and :max items.',
],
'boolean' => 'The :attribute field must be true or false.',
'confirmed' => 'The :attribute confirmation does not match.',
'date' => 'The :attribute is not a valid date.',
'date_equals' => 'The :attribute must be a date equal to :date.',
'date_format' => 'The :attribute does not match the format :format.',
'different' => 'The :attribute and :other must be different.',
'digits' => 'The :attribute must be :digits digits.',
'digits_between' => 'The :attribute must be between :min and :max digits.',
'dimensions' => 'The :attribute has invalid image dimensions.',
'distinct' => 'The :attribute field has a duplicate value.',
'email' => 'The :attribute must be a valid email address.',
'ends_with' => 'The :attribute must end with one of the following: :values.',
'exists' => 'The selected :attribute is invalid.',
'file' => 'The :attribute must be a file.',
'filled' => 'The :attribute field must have a value.',
'gt' => [
'numeric' => 'The :attribute must be greater than :value.',
'file' => 'The :attribute must be greater than :value kilobytes.',
'string' => 'The :attribute must be greater than :value characters.',
'array' => 'The :attribute must have more than :value items.',
],
'gte' => [
'numeric' => 'The :attribute must be greater than or equal :value.',
'file' => 'The :attribute must be greater than or equal :value kilobytes.',
'string' => 'The :attribute must be greater than or equal :value characters.',
'array' => 'The :attribute must have :value items or more.',
],
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'in_array' => 'The :attribute field does not exist in :other.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP address.',
'ipv4' => 'The :attribute must be a valid IPv4 address.',
'ipv6' => 'The :attribute must be a valid IPv6 address.',
'json' => 'The :attribute must be a valid JSON string.',
'lt' => [
'numeric' => 'The :attribute must be less than :value.',
'file' => 'The :attribute must be less than :value kilobytes.',
'string' => 'The :attribute must be less than :value characters.',
'array' => 'The :attribute must have less than :value items.',
],
'lte' => [
'numeric' => 'The :attribute must be less than or equal :value.',
'file' => 'The :attribute must be less than or equal :value kilobytes.',
'string' => 'The :attribute must be less than or equal :value characters.',
'array' => 'The :attribute must not have more than :value items.',
],
'max' => [
'numeric' => 'The :attribute may not be greater than :max.',
'file' => 'The :attribute may not be greater than :max kilobytes.',
'string' => 'The :attribute may not be greater than :max characters.',
'array' => 'The :attribute may not have more than :max items.',
],
'mimes' => 'The :attribute must be a file of type: :values.',
'mimetypes' => 'The :attribute must be a file of type: :values.',
'min' => [
'numeric' => 'The :attribute must be at least :min.',
'file' => 'The :attribute must be at least :min kilobytes.',
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
],
'not_in' => 'The selected :attribute is invalid.',
'not_regex' => 'The :attribute format is invalid.',
'numeric' => 'The :attribute must be a number.',
'password' => 'The password is incorrect.',
'present' => 'The :attribute field must be present.',
'regex' => 'The :attribute format is invalid.',
'required' => 'The :attribute field is required.',
'required_if' => 'The :attribute field is required when :other is :value.',
'required_unless' => 'The :attribute field is required unless :other is in :values.',
'required_with' => 'The :attribute field is required when :values is present.',
'required_with_all' => 'The :attribute field is required when :values are present.',
'required_without' => 'The :attribute field is required when :values is not present.',
'required_without_all' => 'The :attribute field is required when none of :values are present.',
'same' => 'The :attribute and :other must match.',
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
'starts_with' => 'The :attribute must start with one of the following: :values.',
'string' => 'The :attribute must be a string.',
'timezone' => 'The :attribute must be a valid zone.',
'unique' => 'The :attribute has already been taken.',
'uploaded' => 'The :attribute failed to upload.',
'url' => 'The :attribute format is invalid.',
'uuid' => 'The :attribute must be a valid UUID.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap our attribute placeholder
| with something more reader friendly such as "E-Mail Address" instead
| of "email". This simply helps us make our message more expressive.
|
*/
'attributes' => [],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/resources/lang/en/auth.php | resources/lang/en/auth.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used during authentication for various
| messages that we need to display to the user. You are free to modify
| these language lines according to your application's requirements.
|
*/
'failed' => 'These credentials do not match our records.',
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/resources/lang/es/validation.php | resources/lang/es/validation.php | <?php
return [
//TODO: terminar validaciones
// Tomado de: https://parzibyte.me/blog/2019/06/20/laravel-mensajes-validacion-espanol/
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => 'El campo :attribute debe ser aceptado.',
'active_url' => 'El campo :attribute no es una URL válida.',
'after' => 'El campo :attribute debe ser una fecha posterior a :date.',
'after_or_equal' => 'El campo :attribute debe ser una fecha posterior o igual a :date.',
'alpha' => 'El campo :attribute solamente puede contener letras.',
'alpha_dash' => 'El campo :attribute solamente puede contener letras, números, guiones y guiones bajos.',
'alpha_num' => 'El campo :attribute solamente puede contener letras y números.',
'array' => 'El campo :attribute debe ser un arreglo.',
'before' => 'El campo :attribute debe ser una fecha anterior a :date.',
'before_or_equal' => 'El campo :attribute debe ser una fecha anterior o igual a :date.',
'between' => [
'numeric' => 'El campo :attribute debe estar entre :min y :max.',
'file' => 'El campo :attribute debe estar entre :min y :max kilobytes.',
'string' => 'El campo :attribute debe tener entre :min y :max caracteres.',
'array' => 'El campo :attribute debe tener entre :min y :max elementos.',
],
'boolean' => 'El campo :attribute debe ser falso o verdadero.',
'confirmed' => 'El campo de confirmación :attribute no coincide.',
'date' => 'El campo :attribute no es una fecha válida.',
'date_equals' => 'El campo :attribute debe ser una fecha igual a :date.',
'date_format' => 'El campo :attribute no coincide con el formato :format.',
'different' => 'El campo :attribute y :other deben ser diferentes.',
'digits' => 'El campo :attribute debe tener :digits dígitos.',
'digits_between' => 'El campo :attribute debe estar entre :min y :max dígitos.',
'dimensions' => 'El campo :attribute tiene dimensiones de imagen inválidas.',
'distinct' => 'El campo :attribute tiene un valor duplicado.',
'email' => 'El campo :attribute debe ser un correo electrónico válido.',
'exists' => 'El campo seleccionado :attribute es inválido.',
'file' => 'El campo :attribute debe ser un archivo.',
'filled' => 'El campo :attribute debe tener un valor.',
'gt' => [
'numeric' => 'El campo :attribute debe ser mayor que :value.',
'file' => 'El campo :attribute debe ser mayor que :value kilobytes.',
'string' => 'El campo :attribute debe ser mayor que :value caracteres.',
'array' => 'El campo :attribute must have more than :value items.',
],
'gte' => [
'numeric' => 'El campo :attribute debe ser mayor que or equal :value.',
'file' => 'El campo :attribute debe ser mayor que or equal :value kilobytes.',
'string' => 'El campo :attribute debe ser mayor que or equal :value caracteres.',
'array' => 'El campo :attribute must have :value items or more.',
],
'image' => 'El campo :attribute debe ser una imagen.',
'in' => 'El campo seleccionado :attribute es inválido.',
'in_array' => 'El campo :attribute field does not exist in :other.',
'integer' => 'El campo :attribute must be an integer.',
'ip' => 'El campo :attribute must be a valid IP address.',
'ipv4' => 'El campo :attribute must be a valid IPv4 address.',
'ipv6' => 'El campo :attribute must be a valid IPv6 address.',
'json' => 'El campo :attribute must be a valid JSON string.',
'lt' => [
'numeric' => 'El campo :attribute must be less than :value.',
'file' => 'El campo :attribute must be less than :value kilobytes.',
'string' => 'El campo :attribute must be less than :value caracteres.',
'array' => 'El campo :attribute must have less than :value items.',
],
'lte' => [
'numeric' => 'El campo :attribute must be less than or equal :value.',
'file' => 'El campo :attribute must be less than or equal :value kilobytes.',
'string' => 'El campo :attribute must be less than or equal :value caracteres.',
'array' => 'El campo :attribute must not have more than :value items.',
],
'max' => [
'numeric' => 'El campo :attribute no debería ser más grande que :max.',
'file' => 'El campo :attribute no debería pesar más de :max kilobytes.',
'string' => 'El campo :attribute no debería tener más de :max caracteres.',
'array' => 'El campo :attribute no debería tener más de :max elementos.',
],
'mimes' => 'El campo :attribute debe ser un archivo de tipo: :values.',
'mimetypes' => 'El campo :attribute debe ser un archivo de tipo: :values.',
'min' => [
'numeric' => 'El campo :attribute debe ser de al menos :min.',
'file' => 'El campo :attribute debe ser de al menos :min kilobytes.',
'string' => 'El campo :attribute debe ser de al menos :min caracteres.',
'array' => 'El campo :attribute debe tener al menos :min items.',
],
'not_in' => 'El campo seleccionado :attribute es inválido.',
'not_regex' => 'El formato de :attribute es inválido.',
'numeric' => 'El campo :attribute debe ser numérico',
'present' => 'El campo :attribute field debe estar presente.',
'regex' => 'El campo :attribute format es inválido.',
'required' => 'El campo :attribute es obligatorio.',
'required_if' => 'El campo :attribute es obligatorio cuando :other es :value.',
'required_unless' => 'El campo :attribute es obligatorio al menos que :other esté en :values.',
'required_with' => 'El campo :attribute es obligatorio cuando :values está presente.',
'required_with_all' => 'El campo :attribute es obligatorio cuando :values están presentes.',
'required_without' => 'El campo :attribute es obligatorio cuando :values no está presente',
'required_without_all' => 'El campo :attribute es obligatorio cuando ninguno de los valores: :values está presente.',
'same' => 'El campo :attribute y :other deben coincidir.',
'size' => [
'numeric' => 'El campo :attribute must be :size.',
'file' => 'El campo :attribute must be :size kilobytes.',
'string' => 'El campo :attribute must be :size caracteres.',
'array' => 'El campo :attribute debe contener :size elementos.',
],
'starts_with' => 'El campo :attribute con uno de los siguientes valores: :values',
'string' => 'El campo :attribute debe ser una cadena.',
'timezone' => 'El campo :attribute debe ser una zona horaria válida.',
'unique' => 'El campo :attribute ya existe.',
'uploaded' => 'Error al subir :attribute.',
'url' => 'El formato de :attribute es inválido.',
'uuid' => 'El campo :attribute debe ser un UUID válido.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap our attribute placeholder
| with something more reader friendly such as "E-Mail Address" instead
| of "email". This simply helps us make our message more expressive.
|
*/
'attributes' => [],
];
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
parzibyte/sistema_ventas_laravel | https://github.com/parzibyte/sistema_ventas_laravel/blob/a193b0bd30a15df8a95b23fb9ec570f947758942/resources/views/maestra.blade.php | resources/views/maestra.blade.php | {{--
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
Blog: https://parzibyte.me/blog
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/
Contacto: https://parzibyte.me/blog/contacto/
Copyright (c) 2020 Luis Cabrera Benito
Licenciado bajo la licencia MIT
El texto de arriba debe ser incluido en cualquier redistribucion
--}}
<!doctype html>
<html lang="es">
<!--
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
Blog: https://parzibyte.me/blog
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/
Contacto: https://parzibyte.me/blog/contacto/
Copyright (c) 2020 Luis Cabrera Benito
Licenciado bajo la licencia MIT
El texto de arriba debe ser incluido en cualquier redistribucion
-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="{{env("APP_NAME")}}">
<meta name="author" content="Parzibyte">
<title>@yield("titulo") - {{env("APP_NAME")}}</title>
<link href="{{url("/css/bootstrap.min.css")}}" rel="stylesheet">
<link href="{{url("/css/all.min.css")}}" rel="stylesheet">
<style>
body {
padding-top: 70px;
/*Para la barra inferior fija*/
padding-bottom: 70px;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
<a class="navbar-brand" target="_blank" href="//parzibyte.me/blog">{{env("APP_NAME")}}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse"
id="botonMenu" aria-label="Mostrar u ocultar menú">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="menu">
<ul class="navbar-nav mr-auto">
@guest
<li class="nav-item">
<a class="nav-link" href="{{ route('login') }}">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ route('register') }}">
Registro
</a>
</li>
@else
<li class="nav-item">
<a class="nav-link" href="{{route("home")}}">Inicio <i class="fa fa-home"></i></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{route("productos.index")}}">Productos <i class="fa fa-box"></i></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{route("vender.index")}}">Vender <i class="fa fa-cart-plus"></i></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{route("ventas.index")}}">Ventas <i class="fa fa-list"></i></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{route("usuarios.index")}}">Usuarios <i class="fa fa-users"></i></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{route("clientes.index")}}">Clientes <i class="fa fa-users"></i></a>
</li>
@endguest
</ul>
<ul class="navbar-nav ml-auto">
@auth
<li class="nav-item">
<a href="{{route("logout")}}" class="nav-link">
Salir ({{ Auth::user()->name }})
</a>
</li>
@endauth
<li class="nav-item">
<a class="nav-link" href="{{route("soporte.index")}}">Soporte <i
class="fa fa-hands-helping"></i></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{route("acerca_de.index")}}">Acerca de <i class="fa fa-info"></i></a>
</li>
</ul>
</div>
</nav>
<script type="text/javascript">
// Tomado de https://parzibyte.me/blog/2019/06/26/menu-responsivo-bootstrap-4-sin-dependencias/
document.addEventListener("DOMContentLoaded", () => {
const menu = document.querySelector("#menu"),
botonMenu = document.querySelector("#botonMenu");
if (menu) {
botonMenu.addEventListener("click", () => menu.classList.toggle("show"));
}
});
</script>
<main class="container-fluid">
@yield("contenido")
</main>
<footer class="px-2 py-2 fixed-bottom bg-dark">
<span class="text-muted">Punto de venta en Laravel
<i class="fa fa-code text-white"></i>
con
<i class="fa fa-heart" style="color: #ff2b56;"></i>
por
<a class="text-white" href="//parzibyte.me/blog">Parzibyte</a>
|
<a target="_blank" class="text-white" href="//github.com/parzibyte/sistema_ventas_laravel">
<i class="fab fa-github"></i>
</a>
</span>
</footer>
</body>
</html>
| php | MIT | a193b0bd30a15df8a95b23fb9ec570f947758942 | 2026-01-05T05:01:29.026818Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.