how to add product to cart in opencart - opencart

Below is add to product code . But I am not getting where the values are storing . Kindly help to find out solution for this . I want to know logic behind this code
public function add($product_id, $qty = 1, $option = array(), $recurring_id = 0) {
$this->data = array();
$product['product_id'] = (int)$product_id;
if ($option) {
$product['option'] = $option;
}
if ($recurring_id) {
$product['recurring_id'] = (int)$recurring_id;
}
$key = base64_encode(serialize($product));
if ((int)$qty && ((int)$qty > 0)) {
if (!isset($this->session->data['cart'][$key])) {
$this->session->data['cart'][$key] = (int)$qty;
} else {
$this->session->data['cart'][$key] += (int)$qty;
}
}
}

The product details with options are stored in $key = base64_encode(serialize($product));. Where $this->session->data['cart'][$key] contains the number of quantity added by the customer.
For more details check the getProducts() function on the same page. Where you can find
foreach ($this->session->data['cart'] as $key => $quantity) {
....
$product = unserialize(base64_decode($key));
....
}

Related

Symfony get className object from String class declaration

I have this code that returns column names of the className declared in the 2nd line :
public function listColumns(EntityManagerInterface $em ) {
$class = $em->getClassMetadata(Assure::class);
$fields = [];
if (!empty($class->discriminatorColumn)) {
$fields[] = $class->discriminatorColumn['name'];
}
$fields = array_merge($class->getColumnNames(), $fields);
foreach ($fields as $index => $field) {
if ($class->isInheritedField($field)) {
unset($fields[$index]);
}
}
foreach ($class->getAssociationMappings() as $name => $relation) {
if (!$class->isInheritedAssociation($name)){
foreach ($relation['joinColumns'] as $joinColumn) {
$fields[] = $joinColumn['name'];
}
}
}
return $fields;
}
I am trying to make this function parametrable so I can give it every time which table/className I am trying to get its columns
This is a possible solution to do what I want (extracting table column names ) differently :
public function listColumns2(EntityManagerInterface $em ) {
$conn = $this->getEntityManager()->getConnection();
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =
N'Assure' ";
$stmt = $conn->prepare($sql);
$stmt->execute();
return $stmt->fetchAllAssociative();
}

A new entity was found through the relationship?

I have a handle code
if ($this->request->isMethod('POST') && $valid) {
$em = $this->getDoctrine()->getManager();
$formData = $form->getData();
$staffValue = $formData['staff'];
$campaignDetailFilter = $modelCampaignDetail->getRepository()->countDataByCampaignDetailId($formData['campaignDetail']);
$total = count($campaignDetailFilter);
$totalStaff = count($formData['staff']);
foreach ($campaignDetailFilter as $valDetailId) {
$detailDataEntity = $modelDetailData->getEntity($valDetailId['id']);
$batchSize = $total / $totalStaff;
$i = 0;
foreach ($staffValue as $staffVal) {
$detailDataEntity->setStaff($staffVal);
$em->persist($detailDataEntity);
if (($i % $batchSize) === 0) {
$em->flush();
$em->clear();
}
++$i;
}
$em->flush();
$em->clear();
}
}
But when I give $i = 0 it gets an error: A new entity was found through the relationship...that was not configured to cascade persist operations for entity.
You should remove $em->clear().
if (($i % $batchSize) === 0) {
$em->flush();
}

How can I get email from Google People API?

I am using Google people API client library in PHP.
After successfully authenticating, I want to get email
Help me to find out the problem from my code below.
Can i use multiple scopes to get email, beacuse when i m using different scope it gives me error
function getClient() {
$client = new Google_Client();
$client->setApplicationName('People API');
$client->setScopes(Google_Service_PeopleService::CONTACTS);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$str = file_get_contents('credentials.json');
$json = json_decode( $str, true );
$url = $json['web']['redirect_uris'][0];
if (isset($_GET['oauth'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = $url;
header('Location: ' . filter_var($redirect_uri,FILTER_SANITIZE_URL));
} else if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$people_service = new Google_Service_PeopleService($client);
} else {
$redirect_uri = $url.'/?oauth';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
return $people_service;
}
$optParams = array(
'pageSize' => 100,
'personFields' => 'addresses,ageRanges,biographies,birthdays,braggingRights,coverPhotos,emailAddresses,events,genders,imClients,interests,locales,memberships,metadata,names,nicknames,occupations,organizations,phoneNumbers,photos,relations,relationshipInterests,relationshipStatuses,residences,sipAddresses,skills,taglines,urls,userDefined',
);
$people_service = getClient();
$connections = $people_service->people_connections-
>listPeopleConnections('people/me', $optParams);

Zend Regex route reverse with paginator

I have following regex route, which allows me to use pagination - to parse URL and also build it:
; route "product-{brand}"
product.type = "Zend_Controller_Router_Route_Regex"
product.route = "product-([a-z\-]+)(?:/page/(\d+)/?)?"
product.defaults.module = "default"
product.defaults.controller = "products"
product.defaults.action = "product"
product.defaults.page = "1"
product.map.1 = "brand"
product.map.2 = "page"
product.reverse = "product-%s/page/%d"
Everything is working fine, however, I need to get the rid of default page. Currently we are migrating old web to the Zend and we need to preserve old links because of current google positions, etc.
With default "page", I'm getting always /page/1, without it Zend "cannot assemble" URL.
How to not display page 1 in URL ?
Finally, I've managed to achieve this, but only by rewriting Regex assemble method.
I'm simply overriding two methods.
Class extension:
class Utils_Router_Regex extends Zend_Controller_Router_Route_Regex
{
// instantiate
public static function getInstance(Zend_Config $config)
{
$defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
$map = ($config->map instanceof Zend_Config) ? $config->map->toArray() : array();
$reverse = (isset($config->reverse)) ? $config->reverse : null;
return new self($config->route, $defs, $map, $reverse);
}
// in this case, we are using $this->_reverse as array from config
public function assemble($data = array(), $reset = false, $encode = false, $partial = false)
{
//// EXTENSION PART !!!
if( !isset( $data[(string) $this->_reverse->pagemap]) ) { // if not set url helper
$reverse = $this->_reverse->base;
} else { // if set in url helper
$reverse = $this->_reverse->paginator;
}
/// end of extension part
if ($reverse === null) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('Cannot assemble. Reversed route is not specified.');
}
$defaultValuesMapped = $this->_getMappedValues($this->_defaults, true, false);
$matchedValuesMapped = $this->_getMappedValues($this->_values, true, false);
$dataValuesMapped = $this->_getMappedValues($data, true, false);
// handle resets, if so requested (By null value) to do so
if (($resetKeys = array_search(null, $dataValuesMapped, true)) !== false) {
foreach ((array) $resetKeys as $resetKey) {
if (isset($matchedValuesMapped[$resetKey])) {
unset($matchedValuesMapped[$resetKey]);
unset($dataValuesMapped[$resetKey]);
}
}
}
// merge all the data together, first defaults, then values matched, then supplied
$mergedData = $defaultValuesMapped;
$mergedData = $this->_arrayMergeNumericKeys($mergedData, $matchedValuesMapped);
$mergedData = $this->_arrayMergeNumericKeys($mergedData, $dataValuesMapped);
if ($encode) {
foreach ($mergedData as $key => &$value) {
$value = urlencode($value);
}
}
ksort($mergedData);
$return = #vsprintf($reverse, $mergedData);
if ($return === false) {
require_once 'Zend/Controller/Router/Exception.php';
throw new Zend_Controller_Router_Exception('Cannot assemble. Too few arguments?');
}
return $return;
}
}
Then you can define which sprintf string to use:
hodinky.type = "Utils_Router_Regex"
hodinky.route = "hodinky-([a-z\-]+)(?:/page/(\d+)/?)?"
hodinky.defaults.module = "default"
hodinky.defaults.controller = "products"
hodinky.defaults.action = "hodinky"
hodinky.map.1 = "znacka"
hodinky.map.2 = "page"
hodinky.reverse.paginator = "hodinky-%s/page/%d" ; assebmly with paginator
hodinky.reverse.base = "hodinky-%s/" ; assebmly without paginator
hodinky.reverse.pagemap = "page" ; "page" map key
If you have better solution, please let me know.

Group Events by Week Commencing in Eloquent

I have the following method in my Event model for my events:
public static function getEvents($perPage = 10)
{
$events = Event::where('active', '=', 1)->paginate($perPage);
return $events;
}
Each event has a start_date and I need to take that start date and group the results in the view by week commencing, as in the Monday of the week each event occurs. I have this in my controller:
public function index()
{
$events = Event::getEvents($perPage = 5);
$this->layout->content = View::make('events.index')->with('events', $events);
}
Can anyone help me out with grouping these events by week commencing? Thanks.
I'm part way there in terms of getting the week commencing date using:
foreach ($events as $event)
{
$start_date = DateTime::createFromFormat('Y-m-d', $event->start_date);
$week = $start_date->format('YW');
$monday = 1;
$day_offset = ($monday - $start_date->format('N'));
$week_commencing = $start_date->modify("$day_offset days");
$week_commencing = $week_commencing->format('jS F Y');
}
Now I just need to use that to group the events but I'm not sure how to.
EDIT: I feel I'm getting closer to a solution but still need a little help. I now have the below in my controller, and it does print out 1 week commencing then all the events but when var_dump(ing) the $events->weeks_commencing there is only 1 date in the object, so I'm nearly there. Any pointers guys?:
foreach ($events as $event)
{
$start_date = DateTime::createFromFormat('Y-m-d', $event->start_date);
$week = $start_date->format('YW');
$monday = 1;
$day_offset = ($monday - $start_date->format('N'));
$week_commencing = $start_date->modify("$day_offset days");
if (!array_key_exists($week, $events))
{
$events->weeks_commencing = (object) array(
'week' => $week_commencing->format('jS F Y')
);
}
}
EDIT: OK I now have this in my controller. It's getting closer but not quite right yet.
foreach ($events as $event)
{
$start_date = DateTime::createFromFormat('Y-m-d', $event->start_date);
$week = $start_date->format('YW');
$monday = 1;
$day_offset = ($monday - $start_date->format('N'));
$week_commencing = $start_date->modify("$day_offset days");
if (array_key_exists($week, $events))
{
$events = (object) array(
'week' => $week_commencing->format('jS F Y'),
'events' => array()
);
}
$events->events[] = $event;
}
OK, so I've solved my issue now, with the following code:
public function index()
{
$events = Event::getEvents($perPage = 10);
$events_by_week = array();
foreach ($events as $event)
{
$start_date = DateTime::createFromFormat('Y-m-d', $event->start_date);
$week = $start_date->format('YW');
$monday = 1;
$day_offset = ($monday - $start_date->format('N'));
$week_commencing = $start_date->modify("$day_offset days");
if (!array_key_exists($week, $events_by_week))
{
$events_by_week[$week] = (object) array(
'week' => $week_commencing->format('jS F Y'),
'events' => array()
);
}
$events_by_week[$week]->events[] = $event;
}
$this->layout->content = View::make('events.index')->with(array('events_by_week' => $events_by_week, 'events' => $events));
}